try / except (Python)

try/except is how Python handles errors. Code that might fail goes in the try block, and if it raises an exception that an except block names, that block runs instead of the program stopping.

Python

You can target specific exception types, add an else block that runs when no error occurs, and a finally block that always runs (useful for cleanup).

Syntax

try:
    ...
except SomeError:
    ...

Examples

Python

try:
    n = int("abc")
except ValueError:
    print("not a number")

Output:

not a number

Learn it in a lesson

See also

Back to the Dictionary