PCEP Error Handling and Debugging 3 — Questions and Answers
Question 1: What is the base class for all built-in exceptions in Python?
- Exception
- BaseException (Correct answer)
- Error
- RuntimeError
Correct answer: BaseException
`BaseException` is the base class for all built-in exceptions, while `Exception` is a subclass of `BaseException` used for most non-system-exiting exceptions.
Question 2: What does `raise` without any arguments do inside an `except` block?
- Raises a new generic Exception
- Re-raises the currently handled exception (Correct answer)
- Silences the exception
- Raises RuntimeError
Correct answer: Re-raises the currently handled exception
A bare `raise` statement inside an `except` block re-raises the exception currently being handled.
Question 3: Which of the following correctly catches multiple exception types in a single except clause?
- except ValueError, TypeError:
- except [ValueError, TypeError]:
- except (ValueError, TypeError): (Correct answer)
- except ValueError | TypeError:
Correct answer: except (ValueError, TypeError):
Multiple exception types are caught by placing them in a tuple: `except (ValueError, TypeError):`.
Question 4: What exception is raised when a variable is referenced before it has been assigned a value?
- NameError (Correct answer)
- ValueError
- ReferenceError
- AttributeError
Correct answer: NameError
`NameError` is raised when a local or global name cannot be found, which includes using a variable before assigning it.
Question 5: What is the result of this code? def f(): try: return 1 finally: return 2 print(f())
- 1
- 2 (Correct answer)
- None
- An exception is raised
Correct answer: 2
When both `try` and `finally` contain `return`, the `finally` block's `return` overrides the `try` block's `return`.
Question 6: Which exception is raised when a `list.index()` call cannot find the specified value?
- KeyError
- LookupError
- IndexError
- ValueError (Correct answer)
Correct answer: ValueError
`list.index()` raises `ValueError` when the specified value is not present in the list.
Question 7: What is the purpose of the `assert` statement in Python?
- To raise ValueError with a custom message
- To test a condition and raise AssertionError if it is False (Correct answer)
- To suppress exceptions during testing
- To log debugging information to stderr
Correct answer: To test a condition and raise AssertionError if it is False
`assert condition, message` raises `AssertionError` with the optional message if the condition evaluates to False.
What is the base class for all built-in exceptions in Python?