CodeBlanks Logo Icon CodeBlanks

except tuple

Learn tuple exceptions with except (A, B).

Multiple types with except tuple

You can list several error types in a single except block as a parenthesized tuple: except (ValueError, TypeError):. This block catches both types; it's a shortcut when you want to do the same thing.

Using a tuple reduces code repetition. It works for three or more types too: except (ValueError, TypeError, KeyError):. To access the error object you add as e; that's the next lesson.

Why are parens required?

The form except ValueError, TypeError: was valid in Python 2 but is a syntax error in Python 3. Parens are required: except (ValueError, TypeError):. This change is for readability and consistency.

Without parens Python treats the part after the comma as another syntax. So in Python 3 code you always use a parenthesized tuple. Old Python 2 code may show the paren-free form; modern Python won't run it.

Practice Catch two types with a tuple except

In a try block call value = int("abc"). Below it add except (ValueError, TypeError): and inside it write print("Caught"). ValueError matches so this block runs.

Starter code

main.py
# Try a number conversion in a try block
# Catch ValueError and TypeError in one block

Sample solution

main.py
# Call int("abc") in a try block
try:
    value = int("abc")
# Catch with except (ValueError, TypeError):
except (ValueError, TypeError):
    print("Caught")

Expected output

Caught

Questions and answers

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

1 Complete the tuple except

Question
try:
    value = int("x")
except ____:
    print("Error")
Answer
try:
    value = int("x")
except (ValueError, TypeError):
    print("Error")

Explanation: Multi-type except uses a parenthesized tuple.

2 What does except (A, B, C): do?

  • Catches any of A, B or C Correct answer
  • Catches only type A
  • Raises three errors in order
  • Catches only the last type

Explanation: If any type in the tuple matches, the block runs.

3 Match the except tuple concepts

Term Meaning
(A, B) Multi-type tuple
parens Required in Python 3
ValueError Invalid value
TypeError Wrong type

All lessons in Intermediate