Exception Handling: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
Ask the user for a number and print it doubled. Use try / except so that typing letters produces a friendly message instead of a crash.
Catch a ZeroDivisionError when dividing two numbers.
Catch an IndexError when reaching past the end of a list.
Catch a KeyError when asking a dictionary for a key it does not have.
Catch a TypeError from adding a number to a string.
Open a file that does not exist and catch the FileNotFoundError.
Catch an error and print the message Python attached to it, using as.
Write one try with two separate except blocks, and show each one being triggered.
Handle two different exception types in a single except block using a tuple.
Add an else block that runs only when the try block succeeded.
Add a finally block and show that it runs whether or not an error occurred.
Use try / finally with no except at all, to guarantee cleanup while still letting the error travel up.
Write one block using all four clauses and print a marker in each, so the order is obvious.
Keep asking for a number until the user actually types one.
Extend the loop so it also rejects numbers outside a sensible range.
Raise a ValueError yourself when a function is given a value it cannot work with.
Raise a TypeError when an argument is the wrong type, and a ValueError when it is the right type but an impossible value.
Show that except Exception catches almost anything, and explain when that is and is not appropriate.
Show that a parent exception type catches its children, using ArithmeticError and LookupError.
Show that handler order matters: put a general handler before a specific one and explain why the specific one never runs.
Nest one try inside another and show the inner handler dealing with its own error while the outer one waits.
Use assert to state something your code relies on, and catch the AssertionError when it is not true.
Catch an AttributeError and a NameError, and say in a comment what each usually means.
Write safe_divide(a, b) that returns the division or None when it cannot be done, and use it in a loop.
Write read_file(filename) that returns the file's contents, or a message when the file is missing โ the Topic 12 program that could not be written until now.
Write to_int(text, default) that converts text to a whole number, returning the default when it cannot.
Write parse_number(text) that handles whole numbers and decimals, returning None when neither works.
Get a dictionary value two ways โ with .get() and with try / except KeyError โ and say when each reads better.
Write safe_get(items, position, default) that returns a list item or a default, without checking the length first.
Write load_lines(filename) that returns a list of stripped lines, or an empty list when the file is missing, and report which happened.
Write a retry loop that gives up after three attempts and reports failure.
Use finally to guarantee a "session closed" message runs, whichever way the function ends.
Show an exception travelling up through two function calls to be handled at the top.
Define your own exception type and raise it.
Build a small family of custom exceptions with a shared parent, and show that catching the parent catches all of them.
Catch a specific custom exception while letting its sibling pass through to a different handler.
Catch a low-level error and re-raise it as your own, keeping the original attached with raise ... from.
Catch an exception, record that it happened, then re-raise it unchanged with a bare raise.
Show what e.args holds, and pass more than one value when raising.
Convert a list of strings to numbers, skipping the bad ones and reporting what was skipped.
Show the difference between putting try inside a loop and around it.
Validate a record and report every problem with it, not just the first.
Read a CSV of numbers where some rows are malformed, processing the good rows and reporting the bad.
Load a JSON file, coping with both a missing file and a corrupt one.
Write the same operation twice โ once returning a default on failure, once raising โ and say when each is right.
Raise a custom exception from a validation function and catch it where the user can be told.
Show finally running when the try block contains a return, break and continue.
Write deep_get(data, keys) that walks a nested dictionary safely and returns a default if any level is missing.
Simulate an unreliable operation that succeeds on the third attempt, retrying until it works or the limit is reached.
Show why an exception should be caught where something useful can be done about it, rather than as close to the error as possible.
Build a calculator that survives non-numeric input, division by zero, and an unknown operator.
Load a settings file where every value must be the right type, falling back to a default for anything invalid and reporting each substitution.
Build a bank account with custom exceptions for insufficient funds and invalid amounts.
Build an inventory that raises different exceptions for an unknown item and for insufficient stock.
Read student marks from a file where some lines are malformed, producing a report and a list of rejected lines.
Write a temperature converter that validates the unit and the value, raising for each kind of problem.
Build a menu-driven program where every input is validated and no entry can crash it.
Build a login system that allows three attempts and then locks out.
Guard a recursive function against runaway depth, and show Python's own RecursionError as a backstop.
Process several files where some are missing, reporting per file and continuing regardless.
Validate a date given as three numbers, raising a distinct error for each kind of problem.
Build a data-cleaning pipeline that reads raw values, validates them, and reports counts of accepted and rejected at each stage.
Build a shopping cart that validates quantities, checks stock and totals the order, reporting every problem.
Compute an average safely across data that may be empty, contain non-numbers, or be missing entirely.
Build a unit converter that dispatches through a dictionary and raises a clear error for an unknown conversion.
Write a function that saves data and restores the previous version if the save goes wrong.
Validate a whole CSV of records, writing the good rows to one file and a rejection report to another.
Show a percentage calculator that handles an empty denominator in three different ways, and argue for one.
Build a quiz that validates every answer, tolerates bad input, and never loses the score.
Simulate acquiring and releasing a resource, guaranteeing release with finally even when the work fails.
Show why a bare except: is dangerous, using KeyboardInterrupt โ the exception raised when a user presses Ctrl-C.
This program looks fine but hides a genuine bug. Find it.
def total_price(items):
total = 0
for item in items:
try:
total += item["prise"]
except:
pass
return total
print(total_price([{"price": 10}, {"price": 20}, {"price": 30}]))Explain why this function returns "finally" rather than "try".
def confusing():
try:
return "try"
finally:
return "finally"
print(confusing())Show why wrapping too much code in one try block leads to wrong diagnoses.
This reports "no record for Raj" even though Raj's record clearly exists. Explain what the handler is really catching, and fix it.
def lookup_and_report(records, name):
try:
record = records[name]
print(f" found {name}, marks {record['marks']}")
except KeyError:
print(f" no record for {name}")
records = {"Asha": {"marks": [88, 92]}, "Raj": {"score": 74}}
lookup_and_report(records, "Asha")
lookup_and_report(records, "Nobody")
lookup_and_report(records, "Raj")Show what happens when a custom exception does not inherit from Exception.
Show the three ways an exception raised inside a handler can relate to the original.
Show three ways to test which exception you have, and say which belongs in real code.
Show what happens when an exception is raised inside a finally block while another is already travelling.
Explain why assert must never be used to validate user input, and show the correct alternative.
Identify the dead handler in this code and explain why it can never run.
def load(text):
try:
return int(text)
except Exception:
return 0
except ValueError:
return -1
except TypeError:
return -2Show a case where checking first is genuinely unsafe, and why try is the correct answer.
Show why catching an exception and returning a plausible-looking value can be worse than crashing.
Show that an exception raised inside a for loop's body ends the whole loop unless handled inside it, and demonstrate both placements with the same data.
Show three genuinely different responses to the same failure, and explain how to choose between them.
Build a Robust Calculator with a menu, full input validation, an operation history, and no possible crash.
Build a Safe File Manager that reads, appends to and counts lines in a file, coping with every failure the file system can present.
Build a Bank Account with a full custom exception hierarchy, a transaction log, and validation on every operation.
Build a CSV Data Importer that validates every row, writes the clean data, and produces a detailed rejection report with per-error counts.
Build a Student Record System with JSON persistence that survives a missing file, a corrupt file, and every kind of bad input.
Build a Batch Processor that runs a list of jobs, records which succeeded and which failed with what error, and prints a summary that never stops early.
Build a Config Validator that loads a config file, checks every key against a specification of type and range, and reports a full list of problems.
Build an Inventory System with a custom exception hierarchy, where the caller chooses how precisely to react.
Build a Log File Processor that survives malformed lines, missing files and bad numbers, producing a report of what it managed to read.
Build a Retry Manager that runs unreliable operations with a retry limit, records every attempt, and reports which operations eventually succeeded.
Explain EAFP and LBYL, demonstrate both on the same problem, and say when each is the right style in Python.
Set out the exception hierarchy and explain why its shape matters when writing handlers.
Answer the hardest question in this topic: how do you decide whether to catch an exception at all? Give a rule and demonstrate it.
Compare finally, else and with as ways of guaranteeing correct behaviour, and say which to reach for.
Capstone. Build an Exception Toolkit Report. Process a mixed batch of records through a validation pipeline that uses a custom exception hierarchy, else, finally, chaining and retries โ then print a report of what succeeded, what failed, why, and what was recovered.
Still stuck on something?
Book a free 1-on-1 session and we'll work through it together.
Book a Free Session