When a calculation uses text as a number, the conversion or the division can fail. Python’s except clauses let a program catch errors raised inside a try block and choose how to respond.

This article shows how to handle several exception types with one clause when they share a response, and how to use separate clauses when recovery differs.

TL;DR

Use a tuple in one except clause when several exception types need the same response, and separate clauses when their recovery actions differ.

  • The tuple form catches ValueError or TypeError in the same handler.
  • Put more specific exception classes before their parent classes.
  • Catch only errors the code can handle meaningfully.

What Does Catching Multiple Exceptions Mean?

A try block marks the statements to watch. An except clause names exceptions the program can handle.

I put conversion and division in one try block because both steps make up the same calculation, and only the first matching handler runs.

The exception object carries its class and message, and its source can be a function called by the protected code.

A small set of examples shows why choosing a precise type helps decide what response belongs in the handler.

Exception Example cause
TypeError Operation used incompatible types
ValueError Conversion received invalid text
ZeroDivisionError Divisor was zero

An unmatched exception moves through outer try statements until a handler catches it or Python prints a traceback and ends the program.

How to Catch Multiple Exceptions in Python

The example converts text with float() before dividing. I use fixed inputs so each handled failure appears in one repeatable run.

Step 1: Catch errors that share a response

Python accepts a tuple of exception classes after except. The as clause stores the matched exception object in error.

def divide(value, divisor):
    return float(value) / float(divisor)

for value, divisor in [("12", "3"), ("twelve", "3"), ("12", "0")]:
    try:
        print(divide(value, divisor))
    except (ValueError, ZeroDivisionError) as error:
        print(f"{type(error).__name__}: {error}")

Run the example from its saved source file:

python3 multiple_exceptions_demo.py
4.0
ValueError: could not convert string to float: 'twelve'
ZeroDivisionError: division by zero

ValueError identifies the failed conversion, while ZeroDivisionError names the zero denominator. The handled failures leave the script with exit code 0.

Step 2: Use separate clauses for different recovery

The sample separates input errors from arithmetic errors. Replace the fixed strings with values from the application at the point where they enter the program.

user_text = "not-a-number"

try:
    value = float(user_text)
    result = 100 / value
except ValueError as error:
    print("Enter a numeric value:", error)
except ZeroDivisionError:
    print("The value must not be zero")

Run this saved example to see the ValueError branch:

python3 separate_handlers_demo.py
Enter a numeric value: could not convert string to float: 'not-a-number'
Terminal output from separate handlers for a conversion failure

A zero value reaches the second clause. This separate run shows its message:

python3 separate_handlers_zero_demo.py
The value must not be zero
Terminal output from a separate ZeroDivisionError handler

Exception Matching and Edge Cases

I put FileNotFoundError before OSError because the specific exception is a subclass of the broader file-system class.

try:
    open("settings.json")
except FileNotFoundError:
    print("Create the settings file")
except OSError:
    print("Handle another file-system error")

The first branch can point code toward creating a missing file. The broader branch handles other file-system failures with a different response.

A final except Exception can log an unexpected error and re-raise it. I avoid using it for routine recovery because it can catch programming mistakes the function cannot fix.

Python 3.11 and later provides ExceptionGroup with except* for handling matching failures in a group. Any unmatched members still propagate to the caller.

try:
    raise ExceptionGroup("tasks failed", [ValueError("bad input"), OSError("disk")])
except* ValueError as group:
    print("Input failures:", len(group.exceptions))
except* OSError as group:
    print("File failures:", len(group.exceptions))

Run the group example from its source file:

python3 exception_group_demo.py
Input failures: 1
File failures: 1
Terminal output showing ValueError and OSError handled with except star

The output counts one member in each matching subgroup.

A try statement can also have an else clause. Python runs else only when the try body finishes without raising, so success-only work stays outside the code that the except clauses monitor. An error raised inside an except suite is not matched by another clause attached to that same try statement.

For file cleanup, a with statement closes the file after its block even when an exception occurs. This is safer than relying on an except clause to close resources on every failure path.

A custom Exception subclass names an application-specific failure, while raise from preserves a wrapped error’s cause and bare raise propagates the active exception.

Conclusion: Choose the Handler by Recovery

Tuple handlers, separate clauses and except* cover different failure shapes. Test each branch with an input that triggers it, then check that control returns where the caller expects.

For broader try/except behavior, read Python exception handling. For domain-specific errors, see custom exceptions in Python.

FAQ

These answers cover the common syntax choices for handling multiple exceptions in Python.

How do you catch multiple exceptions in Python?

Use separate except clauses for different recovery actions, or put exception classes in a tuple when they share one handler.

Can one except block catch multiple exception types?

Yes. Write the exception classes as a tuple, such as except (ValueError, TypeError):, when the same response is appropriate.

Does an except tuple handle an ExceptionGroup?

No. In Python 3.11 and later, use except* to handle matching exceptions inside an ExceptionGroup.

Share.
Leave A Reply