PCAP Exception Handling 3 — Questions and Answers
Question 1: What is the purpose of the `assert` statement in Python?
- To raise a KeyError
- To test a condition and raise AssertionError if false (Correct answer)
- To skip code blocks
- To assign default values
Correct answer: To test a condition and raise AssertionError if false
`assert` tests a condition and raises `AssertionError` if the condition evaluates to False.
Question 2: Which exception is raised when you try to open a file that does not exist?
- IOError
- FileNotFoundError (Correct answer)
- OSError
- PathError
Correct answer: FileNotFoundError
`FileNotFoundError` is a subclass of `OSError` raised when a file or directory is not found.
Question 3: What happens if an exception is raised inside a `finally` block?
- It is silently ignored
- It replaces any previously raised exception (Correct answer)
- The original exception is re-raised
- The program pauses
Correct answer: It replaces any previously raised exception
An exception raised in a `finally` block replaces and discards any exception currently being propagated.
Question 4: Which exception type is raised when a function receives an argument of the wrong type?
- ArgumentError
- TypeError (Correct answer)
- ValueError
- AttributeError
Correct answer: TypeError
`TypeError` is raised when an operation or function is applied to an object of an inappropriate type.
Question 5: What does `raise` without an argument do inside an `except` block?
- Raises a new RuntimeError
- Re-raises the currently handled exception (Correct answer)
- Suppresses the exception
- Creates a new exception chain
Correct answer: Re-raises the currently handled exception
A bare `raise` statement re-raises the most recently caught exception with its original traceback.
Question 6: Which exception is raised when a function receives an argument with an incorrect value?
- TypeError
- ValueError (Correct answer)
- AttributeError
- RuntimeError
Correct answer: ValueError
`ValueError` is raised when an operation receives an argument of the right type but an inappropriate value.
What is the purpose of the `assert` statement in Python?