Python Exceptions
Handle errors with try/except, raise custom exceptions, and finally blocks
Overview
Exceptions signal runtime errors without crashing the program when handled. Python uses a hierarchy of exception classes; catching specific types is clearer and safer than bare except: clauses.
Syntax / Usage
try:
result = 10 / 0
except ZeroDivisionError as exc:
print(f"Math error: {exc}")
except (ValueError, TypeError):
print("Bad value or type")
else:
print("No exception occurred")
finally:
print("Always runs (cleanup)")
# Raise exceptions
raise ValueError("Age must be positive")
# Custom exception
class AppError(Exception):
pass
Use raise ... from cause to chain exceptions and preserve context.
Examples
Safe integer conversion from user input:
def parse_int(value: str) -> int:
try:
return int(value)
except ValueError as exc:
raise ValueError(f"Not a valid integer: {value!r}") from exc
parse_int("42") # 42
# parse_int("abc") raises ValueError
Read a file with guaranteed cleanup:
def read_config(path):
handle = None
try:
handle = open(path)
return handle.read()
except FileNotFoundError:
return None
finally:
if handle:
handle.close()
Common Mistakes
- Catching bare
ExceptionorBaseExceptionand swallowing errors silently - Using exceptions for normal control flow instead of conditionals
- Forgetting that
finallyruns even whenreturnis intryorexcept - Not re-raising or chaining when wrapping exceptions loses debugging context
See Also
python-file-io python-context-managers python-functions