Loading lessons...
Try...Except Basics
Try...Except Basics
Errors happen. try/except catches them so your program can handle a problem instead of crashing.
The try block
Put risky code in try. The matching except catches any error:
try:
print(x)
except:
print("An exception occurred")
x isn't defined, so the try fails and the except block runs.
Catch a specific error
Name the exception type to handle only that one:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Catch and inspect the error
try:
print(x)
except NameError as e:
print("Problem:", e)
Why it matters
Without try/except, an error stops the whole program. With it, you can react and keep going.
Common built-in exceptions
| Exception | When it happens |
|---|---|
NameError | Name is not defined |
ValueError | Wrong value for a type |
TypeError | Wrong type used |
IndexError | Index out of range |
ZeroDivisionError | Divide by zero |
FileNotFoundError | File is missing |
KeyError | Missing dict key |
TL;DR
tryholds risky code;excepthandles errors.- Name specific exceptions to catch only what you want.
as elets you inspect the error.- Without it, errors crash your program.