Glossary

Try/Except

The try/except statement is Python's mechanism for catching and handling exceptions. Code that might raise an exception goes inside the try block; one or more except clauses specify which exception types to catch and what to do about them. The optional else clause runs only if no exception occurred, and the finally clause runs unconditionally — whether an exception was raised, caught, or not.

The typical structure is: try: (risky code), except SomeError as e: (handle the error, with the exception object bound to e), else: (success path), finally: (cleanup code). Multiple except clauses can catch different exception types, and a single except can catch a tuple of types: except (ValueError, TypeError) as e:. Since Python 3.11, except* handles exception groups from concurrent operations.

Best practice is to catch specific exceptions, not bare except: or except Exception:, because broad catches can mask bugs. Keep the try block as small as possible — only the code that might raise the exception you're handling. Use else for code that should run only on success, and finally for cleanup that must always happen (closing files, releasing locks). The finally clause even runs if the try or except block contains a return statement.

Related terms: Exception, EAFP, Context Manager

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.