Skip to content

Module 12 · Exception Handling — topic 8 of 11

Multiple exception handling

Handling several exception types: one clause with a tuple, separate clauses for different responses, ordering, and exception groups with except* for reporting many errors at once.

Beginner 10 min read·Lesson 190 of 306 in Python Programming

Learning objectives

  • Catch several types with a tuple
  • Respond differently with separate clauses
  • Raise and handle ExceptionGroup with except*

Definition

A try statement can handle several kinds of exception, either with a tuple in a single clause (except (ValueError, TypeError)) or with several except clauses. ExceptionGroup and except* handle several exceptions raised together.

Introduction

Converting user data can fail in several ways: wrong value, wrong type, missing key. Sometimes each needs its own response; sometimes one response fits them all.

Why it matters

Choosing between grouped and separate handlers keeps code short when responses are the same and precise when they differ. Exception groups let validation report every problem, not just the first.

Detailed explanation

Same response: except (ValueError, TypeError) as e: handles both types in one place. The parentheses are required.

Different responses: write one except clause per type. They are checked top to bottom; the first match wins.

Place subclasses before their base classes (FileNotFoundError before OSError), otherwise the specific clause is never reached.

ExceptionGroup (Python 3.11+) bundles several exceptions: raise ExceptionGroup('message', [err1, err2]).

except* TypeError: handles the TypeErrors inside a group; several except* clauses can each handle their part, and eg.exceptions lists the matching exceptions.

Exception groups appear in concurrent code (asyncio.TaskGroup) and in validation, where reporting all errors together is more helpful.

Don't mix except and except* in the same try statement.

Syntax

Python
try:
value = int(data["age"])
except (ValueError, TypeError):
value = None
except KeyError:
print("age missing")
  • Tuple: one response for several types.
  • Separate clauses: different responses.
  • except* handles exception groups.

Code examples

One clause, several types

Python
for v in ["5", "x", None]:
try:
print(int(v) * 2)
except (ValueError, TypeError) as e:
print(type(e).__name__, "handled")
Output
10
ValueError handled
TypeError handled

Separate responses

Python
def lookup(data, key):
try:
return data[key]
except KeyError:
return "no such key"
except IndexError:
return "index out of range"
except TypeError:
return "wrong key type"
print(lookup({"a": 1}, "b"), "|", lookup([1, 2], 7), "|", lookup([1, 2], "a"))
Output
no such key | index out of range | wrong key type

More examples

Reporting every problem with except*

Python
def validate(user):
errors = []
if not user.get("name"):
errors.append(ValueError("name is required"))
if not isinstance(user.get("age"), int):
errors.append(TypeError("age must be an int"))
if errors:
raise ExceptionGroup("invalid user", errors)
return "valid"
print(validate({"name": "Asha", "age": 30}))
try:
validate({"name": "", "age": "30"})
except* ValueError as eg:
for e in eg.exceptions:
print("value problem:", e)
except* TypeError as eg:
for e in eg.exceptions:
print("type problem:", e)
Output
valid
value problem: name is required
type problem: age must be an int

Step-by-step explanation

  • validate collects every problem instead of stopping at the first.
  • ExceptionGroup raises them together.
  • Each except* clause receives a group containing only its matching exceptions, so both handlers run.

Expected output

Running “Reporting every problem with except*” prints exactly:

TextOutput
valid
value problem: name is required
type problem: age must be an int

Practical applications

  • Form validation that highlights all invalid fields.
  • Running several network requests at once and reporting each failure.

Best practices

  • Group types that need the same handling.
  • Use separate clauses when responses differ.
  • Use exception groups when several independent errors matter at once.

Common mistakes

Missing parentheses

Avoid

except ValueError, TypeError:

Prefer

except (ValueError, TypeError):

Multiple types must be given as a parenthesised tuple.

Base class before subclass

Avoid

except OSError: ...
except FileNotFoundError: ...

Prefer

except FileNotFoundError: ...
except OSError: ...

The specific handler would never run.

Important notes

  • except* requires Python 3.11 or newer.

Key takeaways

  • except (A, B) handles several types alike.
  • Separate clauses give different responses; order matters.
  • ExceptionGroup and except* handle many errors together.

Try it yourself

  1. 1
    Write a converter that returns different messages for ValueError, TypeError and OverflowError.
  2. 2
    Extend validate to check an email field and report all problems with except*.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic