Python ยท Advanced Python

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.

Q1try / exceptEasyMust Do

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.

Q2Exception TypesEasy

Catch a ZeroDivisionError when dividing two numbers.

Q3Exception TypesEasy

Catch an IndexError when reaching past the end of a list.

Q4Exception TypesEasy

Catch a KeyError when asking a dictionary for a key it does not have.

Q5Exception TypesEasy

Catch a TypeError from adding a number to a string.

Q6Exception TypesEasyMust Do

Open a file that does not exist and catch the FileNotFoundError.

Q7as eEasyMust Do

Catch an error and print the message Python attached to it, using as.

Q8Multiple HandlersEasyMust Do

Write one try with two separate except blocks, and show each one being triggered.

Q9Multiple HandlersEasy

Handle two different exception types in a single except block using a tuple.

Q10elseEasy

Add an else block that runs only when the try block succeeded.

Q11finallyEasy

Add a finally block and show that it runs whether or not an error occurred.

Q12finallyEasy

Use try / finally with no except at all, to guarantee cleanup while still letting the error travel up.

Q13try / except / else / finallyEasyMust Do

Write one block using all four clauses and print a marker in each, so the order is obvious.

Q14Validation LoopEasyMust Do

Keep asking for a number until the user actually types one.

Q15Validation LoopEasy

Extend the loop so it also rejects numbers outside a sensible range.

Q16raiseEasyMust Do

Raise a ValueError yourself when a function is given a value it cannot work with.

Q17raiseEasy

Raise a TypeError when an argument is the wrong type, and a ValueError when it is the right type but an impossible value.

Q18HierarchyEasy

Show that except Exception catches almost anything, and explain when that is and is not appropriate.

Q19HierarchyEasy

Show that a parent exception type catches its children, using ArithmeticError and LookupError.

Q20HierarchyEasyMust Do

Show that handler order matters: put a general handler before a specific one and explain why the specific one never runs.

Q21Nested tryEasy

Nest one try inside another and show the inner handler dealing with its own error while the outer one waits.

Q22assertEasy

Use assert to state something your code relies on, and catch the AssertionError when it is not true.

Q23Exception TypesEasy

Catch an AttributeError and a NameError, and say in a comment what each usually means.

Q24Safe AccessEasy

Write safe_divide(a, b) that returns the division or None when it cannot be done, and use it in a loop.

Q25File ErrorsEasy

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.

Q26ValidationMedium

Write to_int(text, default) that converts text to a whole number, returning the default when it cannot.

Q27ValidationMedium

Write parse_number(text) that handles whole numbers and decimals, returning None when neither works.

Q28EAFP vs LBYLMediumMust Do

Get a dictionary value two ways โ€” with .get() and with try / except KeyError โ€” and say when each reads better.

Q29Safe AccessMedium

Write safe_get(items, position, default) that returns a list item or a default, without checking the length first.

Q30File ErrorsMedium

Write load_lines(filename) that returns a list of stripped lines, or an empty list when the file is missing, and report which happened.

Q31RetryMedium

Write a retry loop that gives up after three attempts and reports failure.

Q32finallyMedium

Use finally to guarantee a "session closed" message runs, whichever way the function ends.

Q33PropagationMedium

Show an exception travelling up through two function calls to be handled at the top.

Q34Custom ExceptionsMediumMust Do

Define your own exception type and raise it.

Q35Custom ExceptionsMediumMust Do

Build a small family of custom exceptions with a shared parent, and show that catching the parent catches all of them.

Q36Custom ExceptionsMedium

Catch a specific custom exception while letting its sibling pass through to a different handler.

Q37raise fromMedium

Catch a low-level error and re-raise it as your own, keeping the original attached with raise ... from.

Q38Re-raisingMedium

Catch an exception, record that it happened, then re-raise it unchanged with a bare raise.

Q39Exception ObjectsMedium

Show what e.args holds, and pass more than one value when raising.

Q40Batch ProcessingMediumMust Do

Convert a list of strings to numbers, skipping the bad ones and reporting what was skipped.

Q41Batch ProcessingMedium

Show the difference between putting try inside a loop and around it.

Q42ValidationMedium

Validate a record and report every problem with it, not just the first.

Q43File ErrorsMedium

Read a CSV of numbers where some rows are malformed, processing the good rows and reporting the bad.

Q44File ErrorsMediumMust Do

Load a JSON file, coping with both a missing file and a corrupt one.

Q45DesignMedium

Write the same operation twice โ€” once returning a default on failure, once raising โ€” and say when each is right.

Q46Custom ExceptionsMedium

Raise a custom exception from a validation function and catch it where the user can be told.

Q47finallyMedium

Show finally running when the try block contains a return, break and continue.

Q48Safe AccessMedium

Write deep_get(data, keys) that walks a nested dictionary safely and returns a default if any level is missing.

Q49RetryMedium

Simulate an unreliable operation that succeeds on the third attempt, retrying until it works or the limit is reached.

Q50DesignMediumMust Do

Show why an exception should be caught where something useful can be done about it, rather than as close to the error as possible.

Q51Real-WorldMediumMust Do

Build a calculator that survives non-numeric input, division by zero, and an unknown operator.

Q52Real-WorldMedium

Load a settings file where every value must be the right type, falling back to a default for anything invalid and reporting each substitution.

Q53Custom ExceptionsMediumMust Do

Build a bank account with custom exceptions for insufficient funds and invalid amounts.

Q54Custom ExceptionsMedium

Build an inventory that raises different exceptions for an unknown item and for insufficient stock.

Q55File ErrorsMediumMust Do

Read student marks from a file where some lines are malformed, producing a report and a list of rejected lines.

Q56ValidationMedium

Write a temperature converter that validates the unit and the value, raising for each kind of problem.

Q57Real-WorldMediumMust Do

Build a menu-driven program where every input is validated and no entry can crash it.

Q58Real-WorldMedium

Build a login system that allows three attempts and then locks out.

Q59RecursionMedium

Guard a recursive function against runaway depth, and show Python's own RecursionError as a backstop.

Q60File ErrorsMedium

Process several files where some are missing, reporting per file and continuing regardless.

Q61ValidationMedium

Validate a date given as three numbers, raising a distinct error for each kind of problem.

Q62Batch ProcessingMedium

Build a data-cleaning pipeline that reads raw values, validates them, and reports counts of accepted and rejected at each stage.

Q63Real-WorldMedium

Build a shopping cart that validates quantities, checks stock and totals the order, reporting every problem.

Q64Safe AccessMediumMust Do

Compute an average safely across data that may be empty, contain non-numbers, or be missing entirely.

Q65Real-WorldMedium

Build a unit converter that dispatches through a dictionary and raises a clear error for an unknown conversion.

Q66File ErrorsMedium

Write a function that saves data and restores the previous version if the save goes wrong.

Q67ValidationMedium

Validate a whole CSV of records, writing the good rows to one file and a rejection report to another.

Q68DesignMedium

Show a percentage calculator that handles an empty denominator in three different ways, and argue for one.

Q69Real-WorldMedium

Build a quiz that validates every answer, tolerates bad input, and never loses the score.

Q70finallyMedium

Simulate acquiring and releasing a resource, guaranteeing release with finally even when the work fails.

Q71Anti-PatternsHardMust Do

Show why a bare except: is dangerous, using KeyboardInterrupt โ€” the exception raised when a user presses Ctrl-C.

Q72Anti-PatternsHardMust Do

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}]))
Q73finallyHard

Explain why this function returns "finally" rather than "try".

def confusing():
    try:
        return "try"
    finally:
        return "finally"
 
print(confusing())
Q74Anti-PatternsHard

Show why wrapping too much code in one try block leads to wrong diagnoses.

Q75elseHard

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")
Q76Custom ExceptionsHard

Show what happens when a custom exception does not inherit from Exception.

Q77raise fromHard

Show the three ways an exception raised inside a handler can relate to the original.

Q78HierarchyHard

Show three ways to test which exception you have, and say which belongs in real code.

Q79finallyHard

Show what happens when an exception is raised inside a finally block while another is already travelling.

Q80assertHardMust Do

Explain why assert must never be used to validate user input, and show the correct alternative.

Q81Anti-PatternsHard

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 -2
Q82EAFP vs LBYLHard

Show a case where checking first is genuinely unsafe, and why try is the correct answer.

Q83Anti-PatternsHard

Show why catching an exception and returning a plausible-looking value can be worse than crashing.

Q84PropagationHard

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.

Q85DesignHard

Show three genuinely different responses to the same failure, and explain how to choose between them.

Q86Mini-ProjectMini-ProjectMust Do

Build a Robust Calculator with a menu, full input validation, an operation history, and no possible crash.

Q87Mini-ProjectMini-Project

Build a Safe File Manager that reads, appends to and counts lines in a file, coping with every failure the file system can present.

Q88Mini-ProjectMini-Project

Build a Bank Account with a full custom exception hierarchy, a transaction log, and validation on every operation.

Q89Mini-ProjectMini-Project

Build a CSV Data Importer that validates every row, writes the clean data, and produces a detailed rejection report with per-error counts.

Q90Mini-ProjectMini-ProjectMust Do

Build a Student Record System with JSON persistence that survives a missing file, a corrupt file, and every kind of bad input.

Q91Mini-ProjectMini-Project

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.

Q92Mini-ProjectMini-Project

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.

Q93Mini-ProjectMini-Project

Build an Inventory System with a custom exception hierarchy, where the caller chooses how precisely to react.

Q94Mini-ProjectMini-Project

Build a Log File Processor that survives malformed lines, missing files and bad numbers, producing a report of what it managed to read.

Q95Mini-ProjectMini-Project

Build a Retry Manager that runs unreliable operations with a retry limit, records every attempt, and reports which operations eventually succeeded.

Q96InterviewInterview

Explain EAFP and LBYL, demonstrate both on the same problem, and say when each is the right style in Python.

Q97HierarchyInterview

Set out the exception hierarchy and explain why its shape matters when writing handlers.

Q98DesignInterview

Answer the hardest question in this topic: how do you decide whether to catch an exception at all? Give a rule and demonstrate it.

Q99finallyInterview

Compare finally, else and with as ways of guaranteeing correct behaviour, and say which to reach for.

Q100CapstoneInterviewMust Do

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