PCAP-31-03 practice question 24 of 25

If you need to serve two different exceptions called Ex1 and Ex2 in one except branch, you can write:

Full set: 147 questions
Answer options
A: except Ex1 Ex2:
B: except (ex1, Ex2): Correct answer
C: except Ex1, Ex2:
D: except Ex1+Ex2:
Correct Answer:
B. except (ex1, Ex2):
Explanation

In Python you can catch more than one specific exception in a single except-clause by passing a tuple containing the exception classes. The syntax is:

try: ... except (Ex1, Ex2): ...

Because the interpreter expects a tuple after except, only the parenthesised form is accepted.

Why Incorrect

A. Missing comma or parentheses – invalid syntax.
C. “except Ex1, Ex2:” was removed in Python 3; it is a Python 2 construct that bound Ex2 to the caught exception object.
D. The plus sign is not legal grammar in an except-clause.

References

• Python 3.11 Language Reference, “8.4 The try statement”, example: except (RuntimeError, TypeError, NameError): … (https://docs.python.org/3/reference/compoundstmts.html#the-try-statement)

• Van Rossum, G., Drake, F. L. “The Python Language Reference Manual”, §5.3 Exceptions (ISBN 0-596-15810-6), p. 81.

Scroll to Top