How to Handle Errors in Python | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
Python

How to Handle Errors in Python

Learn how to use try/except blocks to handle exceptions and errors in Python.

PythonError HandlingExceptions

Error handling in Python uses try/except blocks to gracefully handle exceptions.

Basic Try/Except

Catch and handle errors:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Catching Multiple Exceptions

Handle different error types:

try:
    value = int("not a number")
except ValueError:
    print("Invalid number format")
except TypeError:
    print("Type error occurred")

Or catch multiple in one block:

try:
    # Some code
    pass
except (ValueError, TypeError) as e:
    print(f"Error: {e}")

Catching All Exceptions

Use with caution:

try:
    # Risky code
    result = risky_operation()
except Exception as e:
    print(f"An error occurred: {e}")

The else Clause

Runs if no exception occurred:

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Division error")
else:
    print(f"Result: {result}")  # Only runs if no error

The finally Clause

Always runs, regardless of exceptions:

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    file.close()  # Always executes
    print("Cleanup complete")

Raising Exceptions

Throw your own exceptions:

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("Age seems unrealistic")
    return age

try:
    validate_age(-5)
except ValueError as e:
    print(f"Validation error: {e}")

Custom Exceptions

Create your own exception classes:

class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Cannot withdraw {amount}. Balance: {balance}")

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount

try:
    withdraw(100, 150)
except InsufficientFundsError as e:
    print(e)  # Cannot withdraw 150. Balance: 100

Common Exceptions

ExceptionWhen it occurs
ValueErrorInvalid value for operation
TypeErrorWrong type for operation
KeyErrorDictionary key not found
IndexErrorList index out of range
FileNotFoundErrorFile doesn’t exist
ZeroDivisionErrorDivision by zero

Summary

  • Use try/except to catch and handle errors
  • Be specific about which exceptions to catch
  • Use else for code that runs only on success
  • Use finally for cleanup code
  • Use raise to throw exceptions