Python Reference ยท Statements and Keywords
The try statement
Reference for the Python try statement: catching exceptions with except, the else and finally clauses, execution order, multiple handlers and common mistakes.
The try statement lets a program react to errors instead of crashing. Code that might fail goes in the try block. If it raises an exception, Python looks for a matching except clause and runs it; if nothing is raised, the optional else clause runs. A finally clause runs in every case, which makes it the right place for cleanup.
Catch only the exceptions you know how to handle. A narrow except keeps real bugs visible.
try: value = int(text) except ValueError: value = 0
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
try: block except ExcType: handler except (TypeA, TypeB) as name: handler else: runs_if_no_exception finally: always_runs
| Clause | Description |
|---|---|
try |
The code to guard. |
except ExcType |
Runs when the exception is an instance of ExcType (or a subclass). A tuple of types matches any of them. as name binds the exception object. |
except (bare) |
Catches everything that derives from BaseException, including KeyboardInterrupt. Avoid it. |
else |
Runs only if the try block finished without raising. Its own errors are not caught by the preceding handlers. |
finally |
Runs always: after success, after a handled error, after an unhandled one, and even on return, break or continue. |
At least one except or a finally is required. Python 3.11 added except* for exception groups.
Usage notes
- First match wins. Handlers are checked top to bottom, so put specific exceptions before general ones.
except Exceptionbeforeexcept ValueErrormakes the second unreachable. - Keep the
tryblock small. Wrap only the statement that can fail, and put the follow-up work inelse, so a bug there is not hidden by the handler. raisealone inside a handler re-raises the active exception with its traceback;raise NewError(...) from errchains a new one.finallybeatsreturn. Areturninfinallyreplaces any earlier return value or pending exception, and silently swallows errors. Avoid it.- The
asname is cleared when theexceptblock ends; copy it first if you need it later. - Exceptions are not free control flow in hot loops, but EAFP style (try, then handle failure) is idiomatic and race-free compared with checking first.
- Never
except: passunless ignoring is truly intended; usecontextlib.suppress(SomeError)to say so explicitly. - Context managers (
with) are usually a neater replacement fortry/finallycleanup.