Python
Exception Handling
Error Catching
Try Except
Programming Techniques

One try block with multiple excepts

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python allows a single try block to have multiple except clauses, each handling a different exception type. This lets you respond to different error conditions with specific recovery logic rather than catching everything with a generic handler. The first matching except block executes, and the rest are skipped.

Basic Syntax

python
1try:
2    result = int(input("Enter a number: "))
3    value = 10 / result
4    print(f"Result: {value}")
5except ValueError:
6    print("That's not a valid number")
7except ZeroDivisionError:
8    print("Cannot divide by zero")
9except Exception as e:
10    print(f"Unexpected error: {e}")

Python checks each except clause top-to-bottom and executes the first one that matches. More specific exceptions should come before general ones.

Catching Multiple Exceptions in One Block

Use a tuple to catch multiple exception types with the same handler:

python
1try:
2    data = json.loads(raw_input)
3    value = data["key"]
4except (json.JSONDecodeError, KeyError, TypeError) as e:
5    print(f"Invalid input data: {e}")

This is useful when several exception types warrant the same response.

Accessing Exception Details

The as keyword binds the exception instance to a variable:

python
1try:
2    with open("config.json") as f:
3        config = json.load(f)
4except FileNotFoundError as e:
5    print(f"Config file missing: {e.filename}")
6except json.JSONDecodeError as e:
7    print(f"Invalid JSON at line {e.lineno}, column {e.colno}")
8except PermissionError as e:
9    print(f"Cannot read file: {e.strerror}")

Different exception types have different attributes — FileNotFoundError has filename, JSONDecodeError has lineno and colno.

Exception Hierarchy Matters

Python exception classes form a hierarchy. A parent class catches all its subclasses:

python
1# OSError is the parent of FileNotFoundError and PermissionError
2try:
3    f = open("data.txt")
4except FileNotFoundError:
5    print("File not found")      # Specific — checked first
6except PermissionError:
7    print("Permission denied")   # Specific — checked second
8except OSError:
9    print("Other OS error")      # General — catches remaining OS errors

If you put OSError first, it would catch FileNotFoundError and PermissionError too, making the specific handlers unreachable:

python
1# BAD: general exception first
2try:
3    f = open("data.txt")
4except OSError:
5    print("OS error")            # Catches ALL OS errors, including the ones below
6except FileNotFoundError:        # Never reached!
7    print("File not found")

Using else and finally

A complete try statement can include else (runs if no exception) and finally (always runs):

python
1try:
2    conn = database.connect()
3    result = conn.execute("SELECT * FROM users")
4except ConnectionError:
5    print("Database connection failed")
6except TimeoutError:
7    print("Query timed out")
8else:
9    # Only runs if no exception was raised
10    users = result.fetchall()
11    print(f"Found {len(users)} users")
12finally:
13    # Always runs — cleanup
14    conn.close()

Real-World Example: API Request Handling

python
1import requests
2
3def fetch_user(user_id):
4    try:
5        response = requests.get(
6            f"https://api.example.com/users/{user_id}",
7            timeout=5
8        )
9        response.raise_for_status()
10        return response.json()
11    except requests.exceptions.ConnectionError:
12        print("Cannot reach the API server")
13    except requests.exceptions.Timeout:
14        print("Request timed out after 5 seconds")
15    except requests.exceptions.HTTPError as e:
16        if e.response.status_code == 404:
17            print(f"User {user_id} not found")
18        elif e.response.status_code == 403:
19            print("Access denied")
20        else:
21            print(f"HTTP error: {e.response.status_code}")
22    except requests.exceptions.JSONDecodeError:
23        print("Response is not valid JSON")
24    return None

Re-raising Exceptions

Use bare raise to re-raise the caught exception after logging or partial handling:

python
1try:
2    process_data(payload)
3except ValueError as e:
4    logger.error(f"Invalid payload: {e}")
5    raise  # Re-raises the same ValueError
6except KeyError as e:
7    raise ValueError(f"Missing required field: {e}") from e  # Chain exceptions

Common Pitfalls

  • Catching Exception too early: Placing except Exception before specific handlers makes them unreachable. Always order from most specific to most general.
  • Bare except: except: (without a type) catches everything, including SystemExit and KeyboardInterrupt. Use except Exception: instead to avoid swallowing system-level signals.
  • Silent failures: Catching an exception and doing nothing (except: pass) hides bugs. At minimum, log the error.
  • Too broad a try block: Wrapping dozens of lines in one try makes it hard to know which line raised the exception. Keep the try block focused on the code that can actually fail.
  • Variable scope: The exception variable (as e) is deleted after the except block exits in Python 3. If you need it later, assign it to another variable first.

Summary

  • A single try block can have multiple except clauses for different exception types
  • Order except blocks from most specific to most general
  • Use (ExcA, ExcB) tuples to handle multiple exceptions the same way
  • Use else for code that should run only when no exception occurs
  • Use finally for cleanup that must always execute
  • Avoid bare except: — prefer except Exception: or specific types

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.