Lecture 13 - Exceptions, Assertions Flashcards
(42 cards)
What is an Exception?
An error that occurs during the runtime of a program, disrupting the normal flow of execution.
What does Raising (or Throwing) an Exception mean?
The act of generating a new exception instance when an error condition is detected.
What is Handling an Exception?
The process of intercepting and responding to a raised exception, preventing the program from crashing.
What is a Try Block?
A block of code that is monitored for potential exceptions.
What is an Except Clause?
A block of code that is executed if a specific type of exception occurs within the associated try block. Multiple except clauses can handle different exception types.
What is the purpose of an Else Clause (Optional)?
A block of code that is executed if and only if no exception was raised within the preceding try block.
What is a Finally Clause (Optional)?
A block of code that is always executed after the try block finishes, regardless of whether an exception was raised or handled. Useful for cleanup operations.
What is an Exception Object?
An instance of a specific exception class, containing information about the error. It can be accessed in the except clause using the as keyword.
What is the Exception Hierarchy?
Exceptions in Python are organised into a class hierarchy. Catching a parent class exception (e.g., Exception) will also catch its subclasses (e.g., ZeroDivisionError).
What are Custom Exceptions?
User-defined exception classes created by subclassing the built-in Exception class or its descendants.
What are Assertions?
Statements used to check if a condition is true. If the condition is false, an AssertionError is raised, halting the program’s execution. Primarily used for debugging and enforcing assumptions during development.
What is __debug__?
A built-in Boolean constant that is True in normal mode and False when Python is run with optimization flags (like -O). Assertions are skipped when __debug__ is False.
What is Defensive Programming?
Writing code with the intention of handling potential errors and unexpected conditions gracefully.
Explain the purpose of exception handling in Python. Why is it important for writing robust programs?
Exception handling allows a program to gracefully recover from runtime errors, preventing it from crashing. This is crucial for robustness as it enables the program to manage unexpected situations, such as invalid user input or file access issues, and continue execution or terminate in a controlled manner.
Describe the structure of a try-except block. What is the role of the try keyword and the except keyword?
A try-except block is used to handle potential exceptions. The code that might raise an exception is placed within the try block. If an exception of a specified type occurs within the try block, the program’s execution immediately jumps to the corresponding except clause, where code to handle that specific exception is located.
What is the significance of specifying the type of exception in an except clause? How does Python determine which except block to execute?
Specifying the exception type in an except clause allows you to handle different kinds of errors in specific ways. Python checks the type of the raised exception against the types listed in the except clauses. The first except clause whose exception type matches the raised exception (or is a superclass of it) will be executed.
Explain the functionality of the optional else clause in a try-except block. Under what circumstances is the code within the else clause executed?
The optional else clause is executed only if the code within the try block completes without raising any exceptions. It is used for code that depends on the successful execution of the try block and should not be run if an error occurred.
Describe the purpose of the finally clause in exception handling. When is the code in a finally block guaranteed to run?
The finally clause is used for code that must be executed regardless of whether an exception was raised in the try block or not, and regardless of whether the exception was handled. It is commonly used for cleanup operations such as closing files or releasing resources.
How can you access the exception object that was caught by an except clause? Provide a brief example.
You can access the exception object using the as keyword in the except clause. For example: try: … except ValueError as e: print(f”A ValueError occurred: {e}”). Here, e is a variable that will hold the instance of the ValueError exception.
What happens to the normal flow of execution within a try block when an exception is raised? What happens to the code following the try-except block?
When an exception is raised within a try block, the remaining code in the try block is skipped, and execution immediately transfers to the appropriate except clause. After the try-except (and optional else and finally) block has finished executing, the program continues with the statement following the entire construct.
Explain the primary use case for assert statements in Python. How do they differ from standard exception handling with try-except?
assert statements are primarily used as a debugging aid to check if certain conditions that should always be true during development are indeed true. If an assertion fails, it indicates a bug in the code. They differ from try-except in that they are intended to halt execution immediately when an unexpected condition arises, rather than gracefully handling anticipated errors.
What is the AssertionError exception? Under what condition is it raised?
AssertionError is the exception raised when an assert statement evaluates the given condition as False. It signals that an assumption made by the programmer about the state of the program has been violated, typically indicating a bug.
How can you disable assert statements in Python? What is the purpose of disabling them in production code?
assert statements can be disabled by running Python in optimized mode using the -O or -OO command-line flags, or by setting the PYTHONOPTIMIZE environment variable. Disabling assertions in production can improve performance by skipping these checks, as it is assumed that the code has been thoroughly debugged and tested.
What is an Arithmetic Exception?
A category of exceptions that occur during arithmetic operations, such as division by zero
Example: ZeroDivisionError