Skip to main content

1. Try, Except, Else, and Finally

Python handles runtime errors using exception blocks. This prevents the application from crashing when an error occurs.

The Basic Try-Except

The try block contains the code that might fail, while the except block catches specific error types and runs recovery logic.

Multiple Error Types

You can catch different errors and handle them differently:

Else and Finally

  • else: Runs only if no exceptions were raised in the try block.
  • finally: Always runs, regardless of whether an exception occurred or was handled. This block is typically used for clean-up tasks (like closing files or database connections).

2. Raising Exceptions

Use the raise keyword to manually trigger a built-in or custom exception when a business logic rule is violated.

3. Custom Exception Classes

For larger applications, Python’s built-in exceptions might not be descriptive enough. You can define domain-specific exceptions by inheriting from Python’s base Exception class.

Defining and Using Custom Exceptions

By convention, name your custom exceptions with the Error suffix.