PCEP-30-02 · Question #242
QUESTION 270 Which of the following snippets shows the correct way of handling multiple exceptions in a single except clause?
The correct answer is B. except (TypeError, ValueError, ZeroDivisionError). Option B is correct because Python requires multiple exception types in a single except clause to be grouped inside a tuple (parentheses), written as except (TypeError, ValueError, ZeroDivisionError):. This syntax tells the interpreter to catch any one of those exception types…
Question
Options
- Aexcept TypeError, ValueError, ZeroDivisionError:
- Bexcept (TypeError, ValueError, ZeroDivisionError):
- Cexcept TypeError, (ValueError, ZeroDivisionError):
- Dexcept (TypeError, (ValueError, ZeroDivisionError)):
- Eexcept TypeError, ValueError, ZeroDivisionError
- Fexcept: (TypeError, ValueError, ZeroDivisionError)
How the community answered
(30 responses)- A3% (1)
- B80% (24)
- D3% (1)
- E3% (1)
- F10% (3)
Explanation
Option B is correct because Python requires multiple exception types in a single except clause to be grouped inside a tuple (parentheses), written as except (TypeError, ValueError, ZeroDivisionError):. This syntax tells the interpreter to catch any one of those exception types with a single handler.
Why the distractors fail:
- A -
except TypeError, ValueError, ZeroDivisionError:is a syntax error in Python 3; in Python 2 the comma syntax was used to bind the exception to a variable (e.g.,except TypeError, e:), but never for multiple types this way. - C & D - Nesting exceptions or mixing comma/tuple styles (
TypeError, (ValueError, ZeroDivisionError)) is invalid syntax; Python does not support nested exception groupings here. - E - Missing the colon (
:) at the end makes it a syntax error regardless of anything else. - F - Putting the tuple after a colon (
except: (...)) catches all exceptions (bareexcept:) and the tuple is just an ignored expression on the next statement - it does not filter by type.
Memory tip: Think of it as a "guest list in parentheses" - you're inviting multiple exception types to one party, and in Python 3 they must all arrive together inside (). No parentheses = no party (syntax error).
Community Discussion
No community discussion yet for this question.