Lesson 89 +10 XP

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

ExceptionWhen it happens
NameErrorName is not defined
ValueErrorWrong value for a type
TypeErrorWrong type used
IndexErrorIndex out of range
ZeroDivisionErrorDivide by zero
FileNotFoundErrorFile is missing
KeyErrorMissing dict key

TL;DR

  • try holds risky code; except handles errors.
  • Name specific exceptions to catch only what you want.
  • as e lets you inspect the error.
  • Without it, errors crash your program.