Exception handling helps identify, catch, and respond to errors in your code, making it easier to debug and maintain.
try
and except
BlocksBy wrapping code in try
and except
blocks, you can catch errors and understand where they occur.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
Custom error messages help pinpoint the issue quickly.
def divide(a, b):
if b == 0:
raise ValueError("The denominator cannot be zero.")
return a / b
try:
divide(10, 0)
except ValueError as e:
print(f"Debug info: {e}")
logging
ModuleThe logging
module allows you to log exceptions, which aids in tracking errors during execution.
import logging
logging.basicConfig(level=logging.ERROR)
try:
result = 10 / 0
except ZeroDivisionError as e:
logging.error("Division by zero occurred", exc_info=True)
Use exception chaining to add context to an exception, helping trace the source of the error.
try:
# Code that raises an exception
raise ValueError("Invalid value")
except ValueError as e:
raise RuntimeError("Error in data processing") from e
Assertions help ensure that certain conditions hold true, providing immediate feedback when they fail.
def validate_age(age):
assert age >= 0, "Age cannot be negative."
try:
validate_age(-5)
except AssertionError as e:
print(f"Assertion failed: {e}")
pdb
ModuleThe pdb
module is Python’s built-in debugger, allowing you to step through code and inspect variables.
import pdb
def calculate(a, b):
pdb.set_trace()
return a / b
calculate(10, 0)