Error Handling and Debugging Flashcards
5 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 5 Error Handling and Debugging flashcards as text
What does the "try...except" block in Python do?
Answer: Catches and handles exceptions or errors that occur during execution
The `try...except` block in Python is a mechanism for handling runtime errors, known as exceptions, gracefully. Code within the `try` block is executed, and if an exception occurs, execution immediately jumps to the `except` block. This allows the program to handle the error without crashing, ensuring more robust and stable execution.
What type of error occurs if you try to access an undefined variable?
Answer: NameError
A `NameError` occurs in Python when you try to use a variable or function name that has not been defined or is not accessible in the current scope. The interpreter cannot find a reference for the name you are trying to access, leading to this specific type of error. It indicates a problem with how a name is referenced in the code.
What is the purpose of the "else" block in a "try...except" structure in Python?
Answer: To execute code if no exceptions are raised in the try block.
In a `try...except...else` structure, the `else` block is executed only if the code within the `try` block runs completely without raising any exceptions. It provides a way to run code that depends on the `try` block's success, separate from the `try` block itself. This helps in organizing code that should only execute when no errors occur.
What does the "finally" block do in "a try...except" structure?
Answer: It executes whether an exception is raised or not.
The `finally` block in a `try...except...finally` structure is guaranteed to execute regardless of whether an exception occurred in the `try` block or was handled by an `except` block. It is typically used for cleanup operations, such as closing files or releasing resources. This ensures that essential finalization steps are always performed, preventing resource leaks.
Which of the following statements is true about debugging in Python?
Answer: The "pdb" module is Python’s built-in debugger that allows you to step through code, set breakpoints, and inspect variables.
Python includes a powerful built-in debugger called `pdb` (Python Debugger). This module allows developers to interactively step through their code line by line, set breakpoints to pause execution at specific points, and inspect the values of variables. This functionality is crucial for identifying, understanding, and fixing bugs in Python programs efficiently.