Catching Multiple Exceptions
You can handle multiple exceptions with a single try block:
or we can combine them like this
The else Block
The else block in Python exception handling is used to define code that should run only if no exception occurs in the try block. It’s a great way to separate the “happy path” logic — the part that should execute when everything goes smoothly — from the error-handling code in the except block. This improves readability and helps keep the code clean and well-organized.
The finally Block
The finally block is used to define a section of code that always executes, no matter what — whether an exception occurs or not. It's typically used for cleanup actions such as closing files, releasing resources, or resetting variables. This ensures that essential steps are not skipped, even if an error is raised or the program exits early.
Raising Exceptions Manually
Sometimes, you may want to proactively raise an exception in your code when a specific condition isn’t met — even if Python wouldn’t naturally throw an error in that situation. This is called raising exceptions manually, and it allows you to enforce rules, validate inputs, or signal unexpected behavior. It’s especially useful in custom applications where you want to stop execution and alert the user or developer to an issue that requires attention.
Creating Custom Exceptions
Sometimes, the built-in exceptions just aren’t descriptive or specific enough for the unique errors that can arise in your application. That’s when user-defined exceptions come into play. You can create your own exception classes to handle custom error conditions more meaningfully.
All user-defined exceptions should inherit from Python’s built-in Exception class (or any subclass of it).
This gives a clean and clear message tailored to the domain logic, instead of just using a generic
ValueError or
Exception.
Always document your custom exceptions well. You can also group multiple custom exceptions under a base exception for your application:
This allows you to catch all app-specific exceptions in one go if needed:
This user-defined exception section makes your blog more complete, especially for intermediate Python developers who want to take their error handling to the next level.