AlgoMaster Logo

Exception Handling - Quiz

Last Updated: December 6, 2025

1 min read

Exception Handling Exercises

32 quizzes

1
Code Completion

Complete the statement so that it explicitly throws a ValueError when the age is invalid.

python
1
error = ValueError()

Click an option to fill the blank:

2
Code Completion

Fill the blank so that the expression checks whether the key 'price' exists in the dictionary product before accessing it.

python
1
has_price = "price" product

Click an option to fill the blank:

3
Code Completion

Complete the statement so that it gets the name of the exception class from the exception object err.

python
1
exc_name = type(err).

Click an option to fill the blank:

4
Multiple Choice

Which statement best describes a Python exception?

5
Multiple Choice

What happens if an exception is raised and not handled by any try-except block?

6
Multiple Choice

In a basic try-except block, where should you place the code that might fail?

7
Multiple Choice

Why is it usually better to catch specific exception types instead of using a bare 'except:'?

8
Multiple Choice

How can you catch both ValueError and ZeroDivisionError with the same handler?

9
Multiple Choice

When does the else block of a try-except-else-finally structure execute?

10
Multiple Choice

What is the primary purpose of the finally block?

11
Multiple Choice

Which keyword is used to intentionally trigger an exception in Python?

12
Multiple Choice

What is a key benefit of creating custom exception classes?

13
Multiple Choice

In exception chaining, what does the 'from' keyword achieve?

14
Multiple Choice

Which pair of special methods must a class implement to be used as a context manager with 'with'?

15
Multiple Choice

What is a common advantage of using the 'with' statement for file operations?

16
Sequencing

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.

17
Sequencing

Order the steps to create and use a custom exception for an invalid configuration value.

Drag and drop to reorder, or use the arrows.

18
Output Prediction

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))
19
Output Prediction

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"))
20
Output Prediction

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)
21
Output Prediction

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")
22
Output Prediction

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__)
23
Bug Spotting

This function should read text from a file and always close it. Identify the bug.

Click on the line(s) that contain the bug.

python
1
def read_text(path):
2
    try:
3
        f = open(path, "r")
4
        data = f.read()
5
        return data
6
    except FileNotFoundError:
7
        return "missing"
8
    finally:
9
        f.close()
24
Bug Spotting

This context manager should suppress only ValueError. Find the bug.

Click on the line(s) that contain the bug.

python
1
class SuppressValueError:
2
    def __enter__(self):
3
        return self
4
    def __exit__(self, exc_type, exc_value, tb):
5
        if isinstance(exc_type, ValueError):
6
            return True
7
        return False
25
Matching

Match 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.

26
Matching

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.

27
Fill in the Blanks

Complete the code to safely convert user input to an integer and log a custom message when the conversion fails.

python
1
def to_int_or_log(text, logger):
2
try:
3
value = int(text)
4
except ValueError:
5
logger.("failed to convert to int")
6
return
7
else:
8
return value

Click an option to fill blank 1:

28
Fill in the Blanks

Complete the custom exception and its use to validate that a configuration timeout is positive.

python
1
class TimeoutConfigError(Exception):
2
def __init__(self, timeout):
3
message =
4
super().__init__(message)
5
6
def validate_timeout(timeout):
7
if timeout <= 0:
8
raise TimeoutConfigError(timeout)
9
return

Click an option to fill blank 1:

29
Fill in the Blanks

Complete the context manager so it opens a file for reading and always closes it.

python
1
class Reader:
2
def __init__(self, path):
3
self.path = path
4
self.file = None
5
def __enter__(self):
6
self.file = (self.path, "r")
7
return self.file
8
def __exit__(self, exc_type, exc_val, exc_tb):
9
if self.file is not None:
10
self.file.()

Click an option to fill blank 1:

30
Fill in the Blanks

Complete the code so that it re-raises the original exception after adding context.

python
1
def load_config(loader):
2
try:
3
return loader()
4
except Exception as original:
5
print("error while loading config")
6
7
8
try:
9
load_config(lambda: 1 / 0)
10
except Exception as final_error:
11
(type(final_error.__cause__).__name__)

Click an option to fill blank 1:

31
Hotspot Selection

Click the line that will raise an exception if the key is missing.

Click on the line to select.

python
1
config = {"host": "example.com"}
2
port = config.get("port", 80)
3
required_host = config["host"]
4
missing_value = config["timeout"]
5
print("ready")
32
Hotspot Selection

Click the line where a finally-style cleanup should occur to always close the connection.

Click on the line to select.

python
1
class Connection:
2
    def close(self):
3
        print("closed")
4
 
5
conn = Connection()
6
try:
7
    print("using connection")
8
finally:
9
    conn.close()

Premium Content

Subscribe to unlock full access to this content and more premium articles.