Skip to main content

4. Basic Error Handling (try / except)

Used to handle runtime errors without crashing the program.

Basic Syntax


Example

Output

Catch Specific Exceptions


Multiple Exceptions


else

Runs only if no exception occurs.
Output

finally

Always executes.
Output

Raising Exceptions


Common Built-in Exceptions


Quick Revision

Error Handling

  • try → Code that may fail.
  • except → Handle exceptions.
  • else → Runs when no exception occurs.
  • finally → Always runs.
  • raise → Manually throw an exception.
  • Catch specific exceptions whenever possible instead of using a bare except.