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
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
- Code in the
tryblock runs normally. - If an exception is raised, Python stops the
tryblock. - Python checks each
exceptclause for a matching exception type. - The first matching
exceptblock runs — this is your recovery code. - If no
exceptmatches, the exception propagates up the call stack.
Related terms
Related Resources
Related Lessons
- Conditions and Loops
Exception handling builds on control flow
Learn the fundamentals
Deepen your understanding with structured lessons on this topic.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.