Exceptions and Error Handling
Handle errors gracefully with try/except/else/finally, raise exceptions, and create custom ones.
What you'll learn
- Use try/except to catch and handle errors
- Understand else and finally clauses
- Raise exceptions with raise and assert
- Create custom exception classes
- Avoid catching too broad or too narrow exceptions
Concept
try / except
Python uses try/except to handle errors (exceptions). Code that might fail goes in the try block; the handling code goes in except:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
result = None
If no exception occurs, the except block is skipped. If an exception of the specified type occurs, the except block runs. If an unlisted exception occurs, it propagates up.
Catching Multiple Exceptions
try:
value = int(input("Enter a number: "))
result = 100 / value
except ValueError:
print("That is not a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
except (TypeError, OverflowError):
print("A different error occurred")
You can catch multiple types in one except by passing a tuple. Always catch specific exceptions — never use a bare except: without a type, as it hides bugs.
else and finally
try:
f = open("data.txt")
except FileNotFoundError:
print("File not found")
else:
# Runs only if NO exception occurred
print(f.read())
f.close()
finally:
# ALWAYS runs, exception or not
print("Cleanup complete")
else— runs only if thetryblock succeeded with no exception. It is cleaner than putting success logic insidetry.finally— always runs, whether an exception occurred or not. Use it for cleanup (closing files, releasing resources).
Raising Exceptions
Use raise to trigger an exception intentionally:
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
# Re-raise an exception after logging
try:
risky_operation()
except Exception as e:
log_error(e)
raise # re-raises the same exception
The raise statement without arguments re-raises the current exception — useful for logging and propagating.
The Exception Hierarchy
All exceptions derive from BaseException. The most common ones:
BaseException
├── SystemExit # sys.exit()
├── KeyboardInterrupt # Ctrl+C
└── Exception
├── StopIteration
├── ArithmeticError
│ └── ZeroDivisionError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── ValueError
├── TypeError
├── FileNotFoundError
└── ...
Catch Exception (not BaseException) if you want to catch all "normal" errors without intercepting SystemExit and KeyboardInterrupt.
Custom Exceptions
Create your own exception classes by inheriting from Exception:
class InvalidAgeError(ValueError):
"""Raised when an age value is invalid."""
pass
def set_age(age):
if age < 0:
raise InvalidAgeError(f"Age cannot be negative: {age}")
return age
Custom exceptions make your error handling more meaningful and let callers catch your specific errors separately from built-in ones.
Getting Exception Details
try:
risky_code()
except Exception as e:
print(f"Error type: {type(e).__name__}")
print(f"Error message: {e}")
The as e syntax binds the exception object to a variable so you can inspect it.
Example
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Caught: {e}")
result = None
print(f"Result: {result}")
# Multiple exception types
try:
value = int("not a number")
result = 100 / value
except ValueError:
print("That is not a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
# else and finally
try:
number = int("42")
except ValueError:
print("Invalid input")
else:
print(f"Success: got {number}")
finally:
print("Cleanup runs always")
# Raising exceptions
def set_age(age):
if age < 0:
raise ValueError(f"Age cannot be negative: {age}")
return age
try:
set_age(-5)
except ValueError as e:
print(f"Validation error: {e}")
# Custom exception
class InvalidScoreError(ValueError):
"""Raised when a test score is out of range."""
pass
def check_score(score):
if not 0 <= score <= 100:
raise InvalidScoreError(f"Score must be 0-100, got {score}")
try:
check_score(150)
except InvalidScoreError as e:
print(f"Score error: {e}")
Demonstrates basic try/except, catching multiple types, else/finally clauses, raising ValueError with a message, re-raising, and a custom exception class inheriting from ValueError.
Try it
- JSON Formatter
JSON parsing errors are common — practice handling malformed input.
- Math Evaluator
Math errors like division by zero are classic exception cases.
Common mistakes
The mistake
Using a bare except: that catches all exceptions including KeyboardInterrupt
The fix
Never use bare 'except:' — it catches SystemExit and KeyboardInterrupt too, making Ctrl+C not work. Use 'except Exception:' at minimum, or better, catch specific exception types.
The mistake
Catching exceptions too broadly and silently ignoring errors
The fix
Avoid 'except Exception: pass' — it hides bugs. Always at least log the exception. Catch only the specific exceptions you expect and know how to handle. Let unexpected errors propagate.
Related Resources
Related Cheatsheets
- Python Cheatsheet
Exception hierarchy and try/except syntax reference.
Practice Exceptions and Error Handling
8 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.