PCAP Exception Handling 2 — Questions and Answers
Question 1: Which exception is raised when dividing by zero in Python?
- ArithmeticError
- ZeroDivisionError (Correct answer)
- MathError
- ValueError
Correct answer: ZeroDivisionError
`ZeroDivisionError` is raised when attempting to divide a number by zero.
Question 2: Which exception is raised when accessing an index that does not exist in a list?
- KeyError
- IndexError (Correct answer)
- ValueError
- TypeError
Correct answer: IndexError
`IndexError` is raised when a sequence subscript is out of range.
Question 3: Which exception is raised when a dictionary key is not found?
- IndexError
- ValueError
- KeyError (Correct answer)
- LookupError
Correct answer: KeyError
`KeyError` is raised when a mapping key is not found in the dictionary.
Question 4: How do you create a custom exception class in Python?
- Inherit from BaseError
- Inherit from Exception (Correct answer)
- Use the @exception decorator
- Inherit from object
Correct answer: Inherit from Exception
Custom exceptions are created by subclassing `Exception` or one of its subclasses.
Question 5: What does `except (TypeError, ValueError):` do?
- Catches only TypeError
- Catches only ValueError
- Catches either TypeError or ValueError (Correct answer)
- Raises both exceptions
Correct answer: Catches either TypeError or ValueError
A tuple of exception types in an except clause catches any of those exception types.
Question 6: Which exception is raised when a variable is used before it is assigned?
- NameError (Correct answer)
- ReferenceError
- AttributeError
- SyntaxError
Correct answer: NameError
`NameError` is raised when a local or global name is not found.
Which exception is raised when dividing by zero in Python?