Python Exception Handling
Exception handling in Python allows you to gracefully manage runtime errors instead of letting your program crash abruptly.
1. The Core Structure: try, except, else, and finally
Python uses blocks of code combined with specific keywords to intercept, handle, and clean up after errors.
try:
# Code that might raise an exception
result = 10 / int(user_input)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter a valid integer.")
else:
# Runs ONLY if no exceptions occurred in the try block
print(f"Success! Result is {result}")
finally:
# Always runs, regardless of whether an exception occurred or not
print("Execution complete. Cleaning up resources...")
Breakdown of Clauses:
try: Wraps the risky code block.except: Catches specific exception types (always catch specific exceptions rather than using a bareexcept:).else: Executes if thetryblock succeeds without raising any errors. Excellent for keeping code insidetryminimal.finally: Guarantees cleanup actions (like closing database connections or files), running even if an exception occurs or areturnstatement is hit.
Advertisement
2. Catching Multiple Exceptions & Accessing Error Details
You can catch multiple exceptions in a tuple or bind the exception instance to a variable using the as keyword to inspect its message:
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except (FileNotFoundError, PermissionError) as e:
print(f"File operation failed: {e}")
Advertisement
3. Raising Exceptions (raise)
You can proactively trigger exceptions using the raise keyword when validation fails or business logic is violated:
def set_age(age):
if age < 0 or age > 120:
raise ValueError("Age must be between 0 and 120.")
return f"Age set to {age}"
try:
set_age(150)
except ValueError as err:
print(err) # Output: Age set to 150 -> wait, Output: Age must be between 0 and 120.
Advertisement
4. Creating Custom Exceptions
When built-in exceptions (ValueError, TypeError, etc.) don't accurately describe your domain errors, you can define custom exceptions by inheriting from Python's built-in Exception class:
# Define a custom exception class
class InsufficientFundsError(Exception):
"""Raised when an account has insufficient funds for a withdrawal."""
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Attempted to withdraw ${amount}, but balance is only ${balance}.")
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
return self.balance
# Usage
account = BankAccount(100)
try:
account.withdraw(150)
except InsufficientFundsError as e:
print(f"Transaction denied: {e}")
Advertisement
5. Exception Handling Best Practices
- Be Specific: Avoid catch-all bare
except:statements. They mask bugs (likeNameErrororSyntaxError) and make debugging excruciating. - Fail Fast: Validate inputs and constraints early in your functions before executing core logic.
- Use Context Managers (
with): For file I/O or network sockets, prefer context managers over manualtry...finallyblocks for automatic resource cleanup.