Skip to main content
Programs encounter unexpected situations at runtime — a file may not exist, user input may be invalid, or a network request may fail. Without exception handling, any of these issues would crash your program. Python’s 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 a try block, and handle specific error types in except blocks:

Catching Multiple Error Types

You can have several except clauses, each targeting a different exception:

else and finally

  • else: Runs only if no exception was raised inside the try block.
  • 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 the raise keyword to manually trigger an exception when a business rule is violated:
Callers can then catch the exception:

Custom Exception Classes

For larger applications, Python’s built-in exceptions may not carry enough domain-specific information. Inherit from Exception (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

Common Built-in Exceptions

Catch the most specific exception you can. Catching the bare Exception class suppresses all errors including bugs you didn’t intend to handle, making debugging much harder.
Never silence exceptions with an empty except block or a bare pass. At minimum, log the error so you know it occurred: