try statement

The statement that runs a block of code and, if a listed exception happens there, runs an except block instead of letting the program stop.

In more detail

The full shape is try, one or more except clauses, an optional else that runs only if nothing was raised, and an optional finally that always runs. List the specific exceptions you expect, such as except ValueError, and keep the try block small, so you do not hide unrelated bugs.

Example

try:
    n = int(text)
except ValueError:
    print("Not a number")

Related terms

Taught in

References

Certification courses