Error Handling Quiz
Quiz
Question 1 of 26
(0 answered)
Question 1
What happens when an exception occurs in a try block and is caught by an except block, followed by an else clause?
โ
Correct!
The else clause only executes if no exception occurs in the try block. If an exception is caught by except, the else block is skipped.
โ
Incorrect
The else clause only executes if no exception occurs in the try block. If an exception is caught by except, the else block is skipped.
Think about the purpose of the else clause - when does it run?
Question 2
The finally block executes only if an exception occurs in the try block.
โ
Correct!
The finally block always executes, whether an exception occurs or not. This makes it perfect for cleanup operations like closing files or releasing resources.
โ
Incorrect
The finally block always executes, whether an exception occurs or not. This makes it perfect for cleanup operations like closing files or releasing resources.
Consider what ‘finally’ means in everyday language.
Question 3
Which of the following are valid reasons to use a finally block?
โ
Correct!
The finally block is for cleanup and actions that must always run. Handling exceptions is done in except blocks, not finally. All other options represent valid cleanup scenarios.
โ
Incorrect
The finally block is for cleanup and actions that must always run. Handling exceptions is done in except blocks, not finally. All other options represent valid cleanup scenarios.
Think about operations that must happen regardless of success or failure.
Question 4
Arrange the exception handling blocks in their correct execution order:
Drag to arrange in the order Python executes them
โฎโฎ
try block
โฎโฎ
else block (if no exception)
โฎโฎ
except block (if exception occurs)
โฎโฎ
finally block
โ
Correct!
Python executes: try โ except (if exception) โ else (if no exception) โ finally (always). The finally block runs last, regardless of what happened before.
โ
Incorrect
Python executes: try โ except (if exception) โ else (if no exception) โ finally (always). The finally block runs last, regardless of what happened before.
Question 5
What gets printed when this code runs?
try:
x = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("Success")
finally:
print("Done")What will this code output?
โ
Correct!
No exception occurs (10/2 is valid), so except is skipped, else executes printing ‘Success’, then finally always executes printing ‘Done’.
โ
Incorrect
No exception occurs (10/2 is valid), so except is skipped, else executes printing ‘Success’, then finally always executes printing ‘Done’.
Trace through each block - does 10/2 raise an exception?
Question 6
In Python’s exception hierarchy, what is the relationship between Exception and ZeroDivisionError?
โ
Correct!
ZeroDivisionError โ ArithmeticError โ Exception โ BaseException. This hierarchy allows catching specific or general exceptions.
โ
Incorrect
ZeroDivisionError โ ArithmeticError โ Exception โ BaseException. This hierarchy allows catching specific or general exceptions.
Look at the exception hierarchy diagram in the content.
Question 7
To create a custom exception, you should inherit from the built-in _____ class.
โ
Correct!
Custom exceptions should inherit from Exception (or its subclasses), not BaseException. This follows Python’s exception hierarchy conventions.
โ
Incorrect
Custom exceptions should inherit from Exception (or its subclasses), not BaseException. This follows Python’s exception hierarchy conventions.
It’s the most common base class for user-defined exceptions.
Question 8
Why is it recommended to catch specific exceptions rather than using a broad
except Exception?โ
Correct!
Catching specific exceptions lets you handle known errors appropriately while allowing unexpected errors to surface. Broad catches can hide bugs and make debugging difficult.
โ
Incorrect
Catching specific exceptions lets you handle known errors appropriately while allowing unexpected errors to surface. Broad catches can hide bugs and make debugging difficult.
Think about what happens when you catch errors you don’t know how to handle.
Question 9
Complete the context manager pattern for automatic file cleanup:
Fill in the missing keyword
_____ open('data.txt', 'r') as f:
content = f.read()
# File automatically closed hereโ
Correct!
The
with statement creates a context manager that handles setup (opening) and cleanup (closing) automatically, even if exceptions occur.โ
Incorrect
The
with statement creates a context manager that handles setup (opening) and cleanup (closing) automatically, even if exceptions occur.Question 10
Context managers created with
@contextmanager must contain a yield statement.โ
Correct!
The
yield statement in a @contextmanager function separates setup (before yield) from cleanup (after yield in finally). It’s required for the decorator to work correctly.โ
Incorrect
The
yield statement in a @contextmanager function separates setup (before yield) from cleanup (after yield in finally). It’s required for the decorator to work correctly.Consider what separates the setup and teardown phases.
Question 11
When should you use
raise without arguments in an except block?โ
Correct!
Using
raise alone re-raises the current exception with its original traceback intact, preserving debugging information. This is useful after logging or cleanup.โ
Incorrect
Using
raise alone re-raises the current exception with its original traceback intact, preserving debugging information. This is useful after logging or cleanup.Think about preserving the original error information.
Question 12
Which scenarios are appropriate for creating custom exceptions?
โ
Correct!
Create custom exceptions for domain-specific or application-specific errors. FileNotFoundError and ZeroDivisionError are already built-in exceptions.
โ
Incorrect
Create custom exceptions for domain-specific or application-specific errors. FileNotFoundError and ZeroDivisionError are already built-in exceptions.
Think about errors specific to your application vs. general Python errors.
Question 13
What is the output of this code?
try:
result = 10 / 0
except ZeroDivisionError:
print("A")
else:
print("B")
finally:
print("C")What will this code output?
โ
Correct!
ZeroDivisionError is caught, so except executes (prints ‘A’). Since an exception occurred, else is skipped. Finally always executes (prints ‘C’).
โ
Incorrect
ZeroDivisionError is caught, so except executes (prints ‘A’). Since an exception occurred, else is skipped. Finally always executes (prints ‘C’).
An exception occurred - which blocks run?
Question 14
What’s the difference between
raise ConfigError('msg') from e and raise ConfigError('msg') from None?โ
Correct!
Use
from e to chain exceptions and preserve the original error for debugging. Use from None when the original exception is irrelevant or would confuse users.โ
Incorrect
Use
from e to chain exceptions and preserve the original error for debugging. Use from None when the original exception is irrelevant or would confuse users.Think about whether you want to show or hide the underlying error.
Question 15
Assertions are suitable for validating user input or handling expected errors.
โ
Correct!
Assertions are for internal checks and programmer errors (bugs). Use exceptions for expected errors like invalid user input. Assertions can be disabled with
python -O, making them unreliable for critical validation.โ
Incorrect
Assertions are for internal checks and programmer errors (bugs). Use exceptions for expected errors like invalid user input. Assertions can be disabled with
python -O, making them unreliable for critical validation.Can assertions be disabled in production?
Question 16
When writing libraries or functions, you should _____ exceptions to signal problems. When calling that code, you should use try/except to _____ those exceptions.
โ
Correct!
Functions should raise exceptions when they detect invalid states (fail fast). Application code should catch those exceptions and decide how to handle them based on context.
โ
Incorrect
Functions should raise exceptions when they detect invalid states (fail fast). Application code should catch those exceptions and decide how to handle them based on context.
Think about the separation of concerns - detecting vs. handling errors.
Question 17
What is the mental model for when to create a custom context manager?
What is the mental model for when to create a custom context manager?
Decision trigger: “If I do X, must I always undo/cleanup Y โ no matter what?”
If yes, create a context manager.
Structure: SETUP โ USE โ CLEANUP (guaranteed)
The core pattern is pairing setup with teardown operations that must always run together โ even if an exception occurs.
Common scenarios:
- Temporary state changes (then restore)
- Resource acquisition/release (files, connections, locks)
- Transaction-like operations (commit/rollback)
- Timing/monitoring (start/end)
- Testing utilities (setup/cleanup)
Did you get it right?
โ
Correct!
โ
Incorrect
Question 18
Which approach is better for handling file operations and why?
โ
Correct!
Context managers (
with open(...)) automatically handle cleanup even if exceptions occur, making code cleaner and less error-prone than manual try/finally blocks.โ
Incorrect
Context managers (
with open(...)) automatically handle cleanup even if exceptions occur, making code cleaner and less error-prone than manual try/finally blocks.Think about automatic vs. manual resource management.
Question 19
Complete the custom exception class:
Fill in the missing class name
class ValidationError(_____):
def __init__(self, field, message):
self.field = field
super().__init__(f"{field}: {message}")โ
Correct!
Custom exceptions should inherit from
Exception (or its subclasses). This follows Python’s exception hierarchy and allows proper exception handling.โ
Incorrect
Custom exceptions should inherit from
Exception (or its subclasses). This follows Python’s exception hierarchy and allows proper exception handling.Question 20
When should you re-raise an exception after catching it?
โ
Correct!
Re-raise when you need to log/cleanup but can’t fully handle the error, or when you need to inspect but not handle certain error types. To suppress errors, use pass (carefully). To convert exceptions, use
raise NewException from e.โ
Incorrect
Re-raise when you need to log/cleanup but can’t fully handle the error, or when you need to inspect but not handle certain error types. To suppress errors, use pass (carefully). To convert exceptions, use
raise NewException from e.Re-raising means the error still propagates up the call stack.
Question 21
What does the
__exit__ method return value control in a custom context manager?โ
Correct!
__exit__ returns False to propagate exceptions (default) or True to suppress them. This gives you control over exception handling in context managers.โ
Incorrect
__exit__ returns False to propagate exceptions (default) or True to suppress them. This gives you control over exception handling in context managers.Think about what happens to exceptions that occur inside the with block.
Question 22
What happens when this code runs?
try:
value = int('abc')
except ValueError:
print('Error')
except TypeError:
print('Type Error')
else:
print('Success')What will this code output?
โ
Correct!
int('abc') raises ValueError (invalid literal), which is caught by the first except block. Once an exception is caught, else is skipped and no other except blocks execute.โ
Incorrect
int('abc') raises ValueError (invalid literal), which is caught by the first except block. Once an exception is caught, else is skipped and no other except blocks execute.What exception does int(‘abc’) raise?
Question 23
You should use
except: (bare except) instead of except Exception: for better error handling.โ
Correct!
Bare
except: catches everything including SystemExit and KeyboardInterrupt, which should usually propagate. Use except Exception: to avoid catching system exceptions, though catching specific exceptions is even better.โ
Incorrect
Bare
except: catches everything including SystemExit and KeyboardInterrupt, which should usually propagate. Use except Exception: to avoid catching system exceptions, though catching specific exceptions is even better.What system-level exceptions should you avoid catching?
Question 24
What is the guideline for deciding where to raise vs. where to catch exceptions?
What is the guideline for deciding where to raise vs. where to catch exceptions?
Raise where errors occur, catch where you can handle them
Functions/libraries should detect invalid states and raise exceptions โ they shouldn’t decide how to handle the error.
Application code that calls functions should catch and handle exceptions based on the context and business requirements.
Did you get it right?
โ
Correct!
โ
Incorrect
Question 25
Which context manager from contextlib would you use to safely delete a file that might not exist?
โ
Correct!
suppress(FileNotFoundError) allows you to ignore specific exceptions cleanly. It’s equivalent to try/except/pass but more explicit and readable.โ
Incorrect
suppress(FileNotFoundError) allows you to ignore specific exceptions cleanly. It’s equivalent to try/except/pass but more explicit and readable.You want to suppress a specific exception type.
Question 26
Which statements about the exception hierarchy are correct?
โ
Correct!
User exceptions should inherit from Exception, not BaseException. All other statements are correct according to Python’s exception hierarchy.
โ
Incorrect
User exceptions should inherit from Exception, not BaseException. All other statements are correct according to Python’s exception hierarchy.
BaseException is for system exceptions. Check the hierarchy tree in the content.
Quiz Results
Score
0/0
Accuracy
0%
Right
0
Wrong
Skipped
0
Last updated on