Error handling in Python means catching and responding to exceptions so a program fails gracefully instead of crashing. You wrap risky code in a try block, handle specific errors in except clauses, run success-only code in else, and put cleanup in finally. Raising your own exceptions with raise signals problems to callers.
Good error handling catches only what you can handle, keeps the original traceback, and logs the failure. This guide uses Python 3.12 and later.
try holds code that may raise.except handles a specific exception type.else runs only if no exception occurred, which keeps the try block small.finally always runs, even after a return or an unhandled exception, so use it for cleanup.Catch the narrowest type you can handle. A bare except: or except Exception: hides bugs and also swallows KeyboardInterrupt in the bare form.
Several types can share one clause with a tuple. The from exc form chains the original error so the traceback shows the cause.
Raise an exception when a function cannot do its job. Create a custom class when callers need to tell your errors apart.
Inherit from Exception, not BaseException. Name classes with an Error suffix.
The with statement is the preferred way to guarantee cleanup. It calls the resource's __exit__ method even when an error occurs, so files, locks and connections are released.
For your own resources, implement __enter__ and __exit__, or use contextlib.contextmanager.
Python 3.11 added ExceptionGroup and the except* syntax for handling multiple unrelated errors raised together, for example by asyncio.TaskGroup.
Each except* clause receives only the matching sub-exceptions.
Log with the logging module rather than print. logger.exception records the traceback automatically inside an except block.
Since Python 3.11 you can call exc.add_note("extra context") to attach information before re-raising.
try blocks short.except: pass. At minimum, log them.raise with no argument to re-raise while preserving the traceback.except Exception and a bare except?A bare except: also catches SystemExit and KeyboardInterrupt, which should normally propagate. except Exception is narrower but still broad, so use it only at top-level boundaries such as a request handler.
finally block run?Always, whether the try block succeeded, raised or returned. It is meant for cleanup, though with statements are often cleaner.
raise ... from ... do?It sets the __cause__ of the new exception to the original, so the traceback shows both and explains why the new error occurred.
No. Assertions are for internal sanity checks and are removed when Python runs with -O. Validate user input with real exceptions.
Handle errors in Python with try, except, else and finally, catch specific exception types, raise custom exceptions to describe failures, use with for cleanup and log with logging. Keep try blocks small and never swallow errors silently.