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.

Practice & Exercises

To reinforce what you’ve learned in this section (try-except blocks, handling multiple errors, else/finally blocks, raising exceptions, and writing custom exceptions), practice with these interactive notebooks:

Follow-Along Practice

Practice catching value errors, handling multiple exceptions like division by zero or file missing, using else and finally, raising validation errors, and subclassing Exception.💻 VS Code | 🚀 Colab | 📥 Download

Practice Exercises

Test your knowledge with hands-on exercises including safe division function, config file loader cleanups, input username verifications, and custom email domain exceptions.💻 VS Code | 🚀 Colab | 📥 Download