Exception

An error raised while a program runs, which you can catch and handle.

An exception is an error that happens while a program runs — as opposed to a syntax error, which is caught before it starts. When something goes wrong (dividing by zero, a missing key, bad input), Python raises an exception that stops the program with a traceback unless you catch it. Wrap risky code in try / except to handle the problem and keep running.

Example
try:
    number = int("not a number")   # this raises ValueError
except ValueError:
    number = 0                     # handle it instead of crashing
print(number)
Output
0

Where this shows up in real Python

Exceptions show up wherever things can go wrong: bad user input, a missing file, a failed network call. Handling them keeps a script from crashing.

Commonly used Exception tools

  • try / except — run risky code and catch failures
  • except ValueError — catch one specific kind of error
  • else / finally — run on success / always run (cleanup)
  • raise — signal an error yourself
  • ValueError, KeyError, FileNotFoundError — common built-in types

Related lessons