Skip to content

Exception

In one line

An exception is an error that occurs while your program runs, which you can catch and handle with try/except.

In simple words

An exception is a runtime error — something that goes wrong while the program is executing. Dividing by zero, opening a missing file, or accessing a list index that does not exist all raise exceptions. If unhandled, the exception crashes the program with a traceback.

Python lets you catch exceptions with try/except blocks. Code that might fail goes in the try block, and the recovery code goes in except. This lets your program handle errors gracefully instead of crashing — show a friendly message, retry, or log the problem.

Every exception is an object with a type (like ZeroDivisionError or FileNotFoundError). You can catch specific types and let others propagate, or catch all exceptions with a bare except:. Good practice is to catch only the exceptions you expect and know how to handle.

Example

python
try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("That was not a valid number.")

try/except catches specific exception types. The program handles the error instead of crashing.

How it works

  1. Code in the try block runs normally.
  2. If an exception is raised, Python stops the try block.
  3. Python checks each except clause for a matching exception type.
  4. The first matching except block runs — this is your recovery code.
  5. If no except matches, the exception propagates up the call stack.

Related terms

Related Resources

Related Lessons

Learn the fundamentals

Deepen your understanding with structured lessons on this topic.

View lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary