Advertisement
❮ Previous: Python Generators & Yield Next: Python Strings & String Formatting ❯

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...")

Try this code ❯

Breakdown of Clauses:


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}")

Try this code ❯


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.

Try this code ❯


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}")

Try this code ❯


Advertisement

5. Exception Handling Best Practices

  1. Be Specific: Avoid catch-all bare except: statements. They mask bugs (like NameError or SyntaxError) and make debugging excruciating.
  2. Fail Fast: Validate inputs and constraints early in your functions before executing core logic.
  3. Use Context Managers (with): For file I/O or network sockets, prefer context managers over manual try...finally blocks for automatic resource cleanup.
❮ Previous: Python Generators & Yield Next: Python Strings & String Formatting ❯
Advertisement