All courses › Intermediate Programming › try / except

try / except

try/except catches and handles errors (exceptions) that occur while the program runs, instead of the whole program crashing. except ValueError: catches only that specific error type, so other errors still get through.

try:…except E:…\text{try}: \ldots \text{except } E: \ldotsrun the block, and handle error type EE if it occurs

Symbols

EEthe error type caught, e.g. ValueError

Example

try:

x = int("abc")

except ValueError:

x = 0

The program continues with x = 0 instead of crashing.

Catch the specific error type you expect — a broad except: easily hides other bugs.
Practise numerics with NumPy for free →

← Matrix operations

Part of Intermediate Programming: Numerics with NumPy.