Python try except: When else and finally Run
Learn how to narrow try blocks, handle specific exceptions, propagate failures, and clean up resources with else and finally.
To handle expected errors in Python, keep the operation that can fail inside a small try block and name the exception types you can recover from in except. Put work that follows a successful operation in else so that an exception of the same type from that work is not accidentally swallowed.
AI-generated conceptual illustration of an exception taking a separate path
This article is based on the Python exception documentation checked on November 19, 2026. The three inputs in the example below were tested with a local Python interpreter.
Narrow the try block and exception type
int("bad") raises ValueError, so the function returns None. "10" prints 10.0. Conversion of "0" succeeds, but the ZeroDivisionError raised in else is not handled by the preceding except ValueError and reaches the outer handler.
The else clause runs when try completes without an exception and without leaving early through return, break, or continue. Exceptions raised in else are not handled by the preceding except clauses of the same statement. Language reference
Log and propagate an exception
An empty except or except Exception: pass hides the failure and its cause when you do not know how to recover. If a higher layer should handle it, log the error and use a bare raise to re-raise the current exception.
This is an illustrative pattern; replace perform_operation with a function from your application. Logs can include paths, personal information, or secrets, so review them before sharing. Raising exceptions
finally and resource cleanup
Under ordinary control flow, finally runs cleanup whether or not an exception was handled. An unhandled exception propagates after cleanup. Avoid return inside finally: it can override a pending exception or return value. Cleanup is not guaranteed if the process is forcibly terminated. Cleanup actions
For resources that support the context manager protocol, such as files, with is usually more concise. It closes the file when leaving the block, but does not automatically recover from failures to open or read it.
The file example is illustrative. In an application, decide whether to print the error, use a default configuration, or propagate it according to the service's failure policy. The with statement and files