Error Handling and Debugging Flashcards
7 cards from real PCEP practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Error Handling and Debugging flashcards as text
What does the `traceback` module help with in Python?
Answer: Formatting and printing stack trace information
The `traceback` module provides utilities for extracting, formatting, and printing Python stack traces for debugging purposes.
What is the difference between `except Exception` and `except BaseException`?
Answer: `except BaseException` also catches SystemExit and KeyboardInterrupt
`BaseException` is the root of all exceptions, so `except BaseException` also catches `SystemExit`, `KeyboardInterrupt`, and `GeneratorExit`, which `except Exception` does not.
Which of the following will raise an `IndexError`?
Answer: my_list = [1, 2]; my_list[5]
Accessing `my_list[5]` on a list with only 2 elements raises `IndexError` because the index is out of the valid range.
What is the output of the following? x = [1, 2, 3] try: print(x[10]) except (IndexError, TypeError) as e: print(type(e).__name__)
Answer: IndexError
Accessing index 10 on a 3-element list raises `IndexError`, and `type(e).__name__` returns the string 'IndexError'.
When is the `else` clause of a try/except structure executed?
Answer: When no exception is raised in the try block
The `else` clause executes only when the `try` block completes without raising any exception.
What is the correct way to raise a ValueError with a custom message?
Answer: raise ValueError('message')
Exceptions are raised by calling them like a class constructor: `raise ValueError('message')` creates an instance and raises it.
What will this code print? try: raise ValueError('oops') finally: print('done')
Answer: done, then the exception propagates
The `finally` block runs and prints 'done' before the unhandled `ValueError` propagates up and terminates the program.