Chapter 9: Errors & Exceptions
Handle runtime errors gracefully, raise your own exceptions, and use assertions for debugging.
Downloadchapter9.py
Objectives
- Distinguish errors vs exceptions in Python.
- Use
try
/except
to catch exceptions. - Leverage
else
andfinally
clauses. - Raise built-in exceptions with
raise
. - Define and use custom exception classes.
- Employ
assert
for sanity checks.
1. Errors vs Exceptions
An error is a problem in your code (syntax, indentation) detected before execution. An exception is a runtime event that can be caught and handled.
# SyntaxError: missing parenthesis
print "Hello"
# ZeroDivisionError at runtime
print(1/0)
2. The try/except Block
Wrap code that may fail in try
, catch specific exceptions in except
.
try:
result = 10 / int(input("Enter divisor: "))
print("Result:", result)
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
3. else & finally
else
runs if no exception occurs; finally
always runs.
try:
f = open("data.txt")
data = f.read()
except FileNotFoundError:
print("Missing file.")
else:
print("Read data:", data[:50])
finally:
f.close()
print("File closed.")
4. Raising Exceptions
Use raise
to trigger an exception manually.
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return True
# call
check_age(-5) # ValueError: Age cannot be negative
5. Custom Exception Classes
Subclass Exception
to define your own.
class InvalidConfigurationError(Exception):
"""Raised when configuration is invalid."""
pass
def load_config(cfg):
if "host" not in cfg:
raise InvalidConfigurationError("Missing host setting")
You can catch it like any built-in exception:
try:
load_config({})
except InvalidConfigurationError as e:
print("Config error:", e)
6. Assertions
Use assert
for internal sanity checks. They can be disabled with -O
.
def factorial(n):
assert n >= 0, "n must be non-negative"
return 1 if n in (0,1) else n * factorial(n-1)
factorial(-1) # AssertionError: n must be non-negative
Exercises
- Write a function that reads an integer and retries until a valid int is entered.
- Create a custom exception
AuthenticationError
and use it in a login function. - Implement file copy with
try/finally
to ensure files are closed. - Add
assert
statements to validate function inputs for a calculator module.