PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Medium
Question 44
Q385 - Error Handling
Which of the following snippets shows the correct way
of handling multiple exceptions in a single except clause?
-
A
- except: TypeError, ValueError, ZeroDivisionError
- # Some code.
-
B
- except TypeError, ValueError, ZeroDivisionError
- # Some code.
-
C
- except (TypeError, ValueError, ZeroDivisionError)
- # Some code.
-
D
- except (TypeError, ValueError, ZeroDivisionError):
- # Some code.
-
E
- except TypeError, ValueError, ZeroDivisionError:
- # Some code.
-
F
- except: (TypeError, ValueError, ZeroDivisionError)
- # Some code.
Reveal correct answer
Correct answer: D
Explanation
Topics: except multiple exceptions
Try it yourself:
- try:
- print(7 / 0)
- except (TypeError, ValueError, ZeroDivisionError):
- print("That is not allowed!")
Explanation:
In Python the colon always has to be at the end of the line.
The list of possible exceptions has to be in parentheses.
Q385 (Please refer to this number, if you want to write me about this question.)
A. This syntax is incorrect for handling multiple exceptions in a single except clause. The correct way is to list the exception types within parentheses after the 'except' keyword, not separated by a colon.
B. This syntax is incorrect for handling multiple exceptions in a single except clause. The correct way is to enclose the exception types within parentheses after the 'except' keyword, not just listing the exception types without parentheses.
C. This syntax is incorrect for handling multiple exceptions in a single except clause. The correct way is to include the exception types within parentheses after the 'except' keyword, not just using parentheses without a colon.
D. The correct way to handle multiple exceptions in a single except clause is to list the exception types within parentheses after the 'except' keyword. This allows the except clause to catch any of the specified exceptions and execute the corresponding code block.
E. This syntax is incorrect for handling multiple exceptions in a single except clause. The correct way is to enclose the exception types within parentheses after the 'except' keyword, not separated by commas.
F. This syntax is incorrect for handling multiple exceptions in a single except clause. The correct way is to list the exception types within parentheses after the 'except' keyword, not just using a colon after 'except'.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
