CodeBlanks Logo Icon CodeBlanks

Multiple except

Learn multiple except blocks.

Multiple except blocks

Some operations can throw different kinds of errors. You can write several except clauses under a single try block; Python picks the first match for the error that occurred.

For example int("abc") raises ValueError, division by zero raises ZeroDivisionError. You can catch each in its own except block and show a specific message for each case. Unmatched error types are not caught and propagate up.

Matching order

except blocks are evaluated top to bottom. You should put the more general one (for example Exception) last; otherwise more specific types never get caught. Because Exception covers nearly all errors.

The right order: specific types first (ValueError, TypeError), then Exception. If you break this rule Python still runs but the right message isn't shown for specific error types; the general block always runs.

Practice Write two except blocks

In a try block call value = int("abc"). Below it add two except blocks: first except ValueError: with print("Value error"), second except ZeroDivisionError: with print("Division by zero error"). The call int("abc") raises ValueError; so the first block runs.

Starter code

main.py
# Try a number conversion in a try block
# Write two except blocks for ValueError and ZeroDivisionError

Sample solution

main.py
# Call int("abc") in a try block
try:
    value = int("abc")
# Write two except blocks for ValueError and ZeroDivisionError
except ValueError:
    print("Value error")
except ZeroDivisionError:
    print("Division by zero error")

Expected output

Value error

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens with multiple except in one try?

  • An error is raised
  • The first matching except runs, the rest are skipped Correct answer
  • Only the last except runs
  • All run in order

Explanation: Python picks the first match top to bottom.

2 Complete the except block

Question
try:
    value = int("abc")
____ ValueError:
    print("Value error")
Answer
try:
    value = int("abc")
except ValueError:
    print("Value error")

Explanation: The except keyword starts error handling.

3 Match the exception types

Term Meaning
ValueError Invalid value
TypeError Wrong type
ZeroDivisionError Division by zero
KeyError Missing key

All lessons in Intermediate