PCAP Exception Handling 1 — Questions and Answers
Question 1: Which keyword is used to handle exceptions in Python?
- catch
- handle
- except (Correct answer)
- rescue
Correct answer: except
The `except` clause in a `try` block is used to catch and handle exceptions.
Question 2: What happens if no exception is raised in a `try` block that has an `else` clause?
- The else block is skipped
- The else block is executed (Correct answer)
- A warning is issued
- The program restarts
Correct answer: The else block is executed
The `else` block runs only when no exception is raised in the `try` block.
Question 3: Which block always executes regardless of whether an exception occurred?
- try
- except
- else
- finally (Correct answer)
Correct answer: finally
The `finally` block always runs whether or not an exception was raised, used for cleanup.
Question 4: How do you raise a custom exception in Python?
- throw Exception('msg')
- raise Exception('msg') (Correct answer)
- error Exception('msg')
- trigger Exception('msg')
Correct answer: raise Exception('msg')
Python uses the `raise` keyword to manually throw an exception.
Question 5: What is the base class for all built-in exceptions in Python?
- Exception
- BaseException (Correct answer)
- Error
- RuntimeError
Correct answer: BaseException
`BaseException` is the root of the Python exception hierarchy; `Exception` is its subclass for non-system-exiting exceptions.
Question 6: What does `except Exception as e:` allow you to do?
- Re-raise the exception
- Access the exception object via the variable `e` (Correct answer)
- Suppress all exceptions
- Skip the except block
Correct answer: Access the exception object via the variable `e`
The `as e` clause binds the caught exception object to the name `e` for inspection.
Which keyword is used to handle exceptions in Python?