try/except mechanism lets you gracefully detect and respond to errors, keep your application running, and communicate failures clearly. This page covers the full exception-handling toolkit: basic try/except, multiple error types, else/finally, raising exceptions, and writing your own custom exception classes.
try, except, else, and finally
Basic try-except
Wrap potentially failing code in atry block, and handle specific error types in except blocks:
Catching Multiple Error Types
You can have severalexcept clauses, each targeting a different exception:
else and finally
else: Runs only if no exception was raised inside thetryblock.finally: Always runs, whether or not an exception occurred — ideal for clean-up tasks.
Use
finally for releasing resources — closing files, database connections, network sockets — so they are always cleaned up even when exceptions occur.Raising Exceptions
Use theraise keyword to manually trigger an exception when a business rule is violated:
Custom Exception Classes
For larger applications, Python’s built-in exceptions may not carry enough domain-specific information. Inherit fromException (or a more specific built-in) to create your own:
1
Define the custom exception
Inherit from
Exception. By convention, use an Error suffix.2
Raise it in business logic
3
Catch and handle it