Skip to content
Tutorials Center
My learning

Topics

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.

Python
try:
    value = int(text)
except ValueError:
    value = 0

Try it

Python Order of execution

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.

Python Several exceptions, re-raising and as-names

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

Python
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 Exception before except ValueError makes the second unreachable.
  • Keep the try block small. Wrap only the statement that can fail, and put the follow-up work in else, so a bug there is not hidden by the handler.
  • raise alone inside a handler re-raises the active exception with its traceback; raise NewError(...) from err chains a new one.
  • finally beats return. A return in finally replaces any earlier return value or pending exception, and silently swallows errors. Avoid it.
  • The as name is cleared when the except block 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: pass unless ignoring is truly intended; use contextlib.suppress(SomeError) to say so explicitly.
  • Context managers (with) are usually a neater replacement for try/finally cleanup.