Python Exception Handling
In this page:
try:
# code that may raise an error
except ExceptionType:
# handle the error
What is an Exception?
An exception is an error Python detects while your program is running (as opposed to a syntax error caught before it even starts) -- if nothing handles it, the exception propagates up and crashes the program with a traceback, which is why handling matters for code that shouldn't just stop unexpectedly.
Example: What is an Exception?
try:
print(1 / 0) # raises ZeroDivisionError at runtime
except ZeroDivisionError:
print("Caught an exception instead of crashing")
Built-in Exceptions
Python ships with many specific built-in exception types -- ZeroDivisionError, TypeError, ValueError, and more -- and catching the specific type you expect (rather than a bare except) makes your error handling precise instead of accidentally swallowing unrelated bugs.
Example: Built-in Exceptions
try:
int("abc")
except ValueError: # catches only this specific error type
print("Caught a specific ValueError")
Raising Exceptions
The raise keyword lets your own code deliberately trigger an exception, which is how you signal 'this input is invalid' from deep inside a function -- raise ValueError('age must be positive') stops execution there and lets a caller's except block decide how to respond.
Example: Raising Exceptions
def set_age(age):
if age < 0:
raise ValueError("age must be positive") # deliberately triggers an exception
return age
try:
set_age(-5)
except ValueError as e:
print(e)
Creating Custom Exceptions
Subclassing the built-in Exception class lets you create your own exception types specific to your application's domain (like InsufficientFundsError), which makes error handling code more readable than checking for generic exceptions and guessing what actually went wrong.
Example: Creating Custom Exceptions
class InsufficientFundsError(Exception): # custom exception type for this domain
pass
try:
raise InsufficientFundsError("Not enough balance")
except InsufficientFundsError as e:
print(e)
Exception Hierarchy
Every built-in exception ultimately inherits from the base Exception class, so an except Exception: block will catch essentially any error your code raises -- but catching that broadly is usually too blunt for production code, since it also hides bugs you'd want to know about.
Example: Exception Hierarchy
try:
int("abc")
except Exception as e: # catches virtually any error, since all inherit from Exception
print("Caught by the base Exception class:", type(e).__name__)
- Reading an error message only for its last line, when the traceback shows where the problem started.
- Raising a string, as in
raise "error", which is aTypeError; raise an exception instance such asValueError("bad"). - Using exceptions for normal flow control, when a simple
ifcheck would be clearer.
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: