PCEP Error Handling and Debugging 2 — Questions and Answers
Question 1: What happens when a `try` block raises an exception that has no matching `except` clause?
- The exception is silently ignored
- Python searches for a matching handler up the call stack (Correct answer)
- The program automatically restarts
- Python converts it to a warning
Correct answer: Python searches for a matching handler up the call stack
If no matching `except` clause is found in the current `try` block, Python propagates the exception up the call stack looking for a handler.
Question 2: Which clause in a try/except structure always executes, whether or not an exception occurred?
- except
- else
- finally (Correct answer)
- raise
Correct answer: finally
The `finally` clause always executes regardless of whether an exception was raised or caught.
Question 3: What does the following code print? try: x = 1 / 0 except ZeroDivisionError: print('A') else: print('B') finally: print('C')
- A
- B C
- A C (Correct answer)
- A B C
Correct answer: A C
The `except` block prints 'A' because a ZeroDivisionError is raised, `else` is skipped, and `finally` always prints 'C'.
Question 4: Which built-in exception is raised when an operation receives the correct type but an inappropriate value?
- TypeError
- ValueError (Correct answer)
- AttributeError
- IndexError
Correct answer: ValueError
`ValueError` is raised when a function receives an argument of the correct type but an invalid value, such as `int('abc')`.
Question 5: What is the output of this code? try: print(1) raise ValueError print(2) except ValueError: print(3) print(4)
- 1 2 3 4
- 1 3 4 (Correct answer)
- 1 3
- 3 4
Correct answer: 1 3 4
Python prints 1, then the ValueError is raised skipping print(2), the except block prints 3, and execution continues with print(4).
Question 6: How do you access the exception object inside an `except` clause?
- except Exception(e):
- except Exception as e: (Correct answer)
- except Exception, e:
- except (Exception) e:
Correct answer: except Exception as e:
The syntax `except ExceptionType as e:` binds the exception instance to the variable `e` for use within the handler.
Question 7: Which exception is raised when you try to access a dictionary key that does not exist?
- IndexError
- ValueError
- KeyError (Correct answer)
- AttributeError
Correct answer: KeyError
`KeyError` is raised when a dictionary is accessed with a key that is not present in it.
What happens when a `try` block raises an exception that has no matching `except` clause?