Last Updated: December 6, 2025
32 quizzes
Complete the statement so that it explicitly throws a ValueError when the age is invalid.
error = ValueError()Click an option to fill the blank:
Fill the blank so that the expression checks whether the key 'price' exists in the dictionary product before accessing it.
has_price = "price" productClick an option to fill the blank:
Complete the statement so that it gets the name of the exception class from the exception object err.
exc_name = type(err).Click an option to fill the blank:
Which statement best describes a Python exception?
What happens if an exception is raised and not handled by any try-except block?
In a basic try-except block, where should you place the code that might fail?
Why is it usually better to catch specific exception types instead of using a bare 'except:'?
How can you catch both ValueError and ZeroDivisionError with the same handler?
When does the else block of a try-except-else-finally structure execute?
What is the primary purpose of the finally block?
Which keyword is used to intentionally trigger an exception in Python?
What is a key benefit of creating custom exception classes?
In exception chaining, what does the 'from' keyword achieve?
Which pair of special methods must a class implement to be used as a context manager with 'with'?
What is a common advantage of using the 'with' statement for file operations?
Order the steps to safely read integers from a text file and handle missing file and bad formatting separately.
Drag and drop to reorder, or use the arrows.
Order the steps to create and use a custom exception for an invalid configuration value.
Drag and drop to reorder, or use the arrows.
What is the output of this code?
1def safe_div(a, b):
2 try:
3 result = a / b
4 except ZeroDivisionError as e:
5 return f"error: {type(e).__name__}"
6 else:
7 return f"ok: {result}"
8
9print(safe_div(6, 3))What is the output of this code?
1def parse_port(text):
2 try:
3 port = int(text)
4 except ValueError:
5 return "invalid"
6 finally:
7 pass
8 return f"port={port}"
9
10print(parse_port("xyz"))What is the output of this code?
1def check_positive(n):
2 if n <= 0:
3 raise ValueError("must be positive")
4 return "ok"
5
6try:
7 msg = check_positive(0)
8except ValueError as err:
9 msg = str(err)
10
11print(msg)What is the output of this code?
1class SilentManager:
2 def __enter__(self):
3 return self
4 def __exit__(self, exc_type, exc_value, tb):
5 return True
6
7try:
8 with SilentManager():
9 raise RuntimeError("boom")
10 print("after")
11except RuntimeError:
12 print("caught")What is the output of this code?
1def outer():
2 try:
3 int("x")
4 except ValueError as e:
5 raise TypeError("wrapped") from e
6
7try:
8 outer()
9except TypeError as err:
10 print(type(err.__cause__).__name__)This function should read text from a file and always close it. Identify the bug.
Click on the line(s) that contain the bug.
def read_text(path): try: f = open(path, "r") data = f.read() return data except FileNotFoundError: return "missing" finally: f.close()This context manager should suppress only ValueError. Find the bug.
Click on the line(s) that contain the bug.
class SuppressValueError: def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if isinstance(exc_type, ValueError): return True return FalseMatch each exception-related concept to its best description.
Click an item on the left, then click its match on the right. Click a matched item to unmatch.
Match each context manager concept with what it is responsible for.
Click an item on the left, then click its match on the right. Click a matched item to unmatch.
Complete the code to safely convert user input to an integer and log a custom message when the conversion fails.
def to_int_or_log(text, logger): try: value = int(text) except ValueError: logger.("failed to convert to int") return else: return valueClick an option to fill blank 1:
Complete the custom exception and its use to validate that a configuration timeout is positive.
class TimeoutConfigError(Exception): def __init__(self, timeout): message = super().__init__(message)def validate_timeout(timeout): if timeout <= 0: raise TimeoutConfigError(timeout) return Click an option to fill blank 1:
Complete the context manager so it opens a file for reading and always closes it.
class Reader: def __init__(self, path): self.path = path self.file = None def __enter__(self): self.file = (self.path, "r") return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file is not None: self.file.()Click an option to fill blank 1:
Complete the code so that it re-raises the original exception after adding context.
def load_config(loader): try: return loader() except Exception as original: print("error while loading config") try: load_config(lambda: 1 / 0)except Exception as final_error: (type(final_error.__cause__).__name__)Click an option to fill blank 1:
Click the line that will raise an exception if the key is missing.
Click on the line to select.
config = {"host": "example.com"}port = config.get("port", 80)required_host = config["host"]missing_value = config["timeout"]print("ready")Click the line where a finally-style cleanup should occur to always close the connection.
Click on the line to select.
class Connection: def close(self): print("closed") conn = Connection()try: print("using connection")finally: conn.close()