🐍 Python for Everyone

← Back to exercises

Chapter 12 Practice Bank 60-80 min, hands-on

Practice Bank: Exception Handling

A deeper set of practice problems, organized by topic, for extra reps beyond the main exercises — including scenario-based problems written in the same style you'll meet in real interviews. Uses everything from Chapters 1-11 plus this chapter's own toolkit: try/except/else/finally, accessing the exception object (as e, str(e)), raise (including re-raising), and custom exception classes that subclass Exception. No file I/O, no other class besides a custom exception subclassing Exception, and no import beyond math/datetime/random.

A note on randomness and dates Any problem using random or datetime.date.today() prints a different result every time you run it — that's the point. solution.py checks a property of the result (like "is this in range") instead of one exact value, so your output won't match anyone else's line-for-line, and that's fine.
How to run these Download starter.py below, then run it from a terminal with python3 starter.py.

Topic 1: Try/Except Basics

1 Safe integer parsing

Find # TODO 1.1. Write safe_int(text), returning int(text) inside a try, or None if a ValueError is raised.

2 Safe division

Find # TODO 1.2. Write safe_divide(a, b), catching ZeroDivisionError and returning None.

3 Safe list indexing

Find # TODO 1.3. Write safe_list_get(items, index), catching IndexError for an out-of-range index.

4 Safe dictionary lookup

Find # TODO 1.4. Write safe_dict_get(data, key), catching KeyError for a missing key.

5 Debug the Code

Find # TODO 1.5. This function is supposed to catch a bad int() conversion, but its except clause catches the wrong exception type entirely. Fix it.

💼 Scenario

Validating form input

Find # TODO 1.A. Write parse_age_field(text) for a signup form that must not crash just because someone typed letters into an age box.

💼 Interview Prep

What if nothing goes wrong?

Find # TODO 1.B. Write explain_no_exception_case(), explaining what happens if no exception is raised inside a try block at all.

Topic 2: Multiple Except Blocks, Else, Finally

1 Separate except blocks

Find # TODO 2.1. Write describe_error(a, b), using separate except ZeroDivisionError and except TypeError blocks.

2 Using else for the success path

Find # TODO 2.2. Write divide_with_message(a, b), using try/except/else so the success message only builds when no error occurred.

3 Using finally for cleanup

Find # TODO 2.3. Write parse_with_finally(text), using a finally block that always runs regardless of success or failure.

4 Combining except and else

Find # TODO 2.4. Write lookup_with_fallback(data, key), returning a fallback only when the lookup actually failed.

5 Debug the Code

Find # TODO 2.5. This function's except blocks are ordered so a more specific exception can never be reached. Fix the order.

💼 Scenario

Payment processing cleanup

Find # TODO 2.A. Write process_payment(amount), using finally to always run a cleanup step regardless of whether the payment succeeded.

💼 Interview Prep

else vs. the end of try

Find # TODO 2.B. Write explain_else_vs_try_tail(), explaining the difference between putting code in else versus leaving it at the end of try.

Topic 3: The Exception Object

1 Reading a ValueError's message

Find # TODO 3.1. Write describe_value_error(text), catching ValueError as e and returning str(e).

2 Reading a ZeroDivisionError's message

Find # TODO 3.2. Write describe_zero_division(a, b), catching ZeroDivisionError as e and returning str(e).

3 Getting the exception's type name

Find # TODO 3.3. Write error_type_name(func, *args), catching Exception as e and returning type(e).__name__.

4 A KeyError's own message

Find # TODO 3.4. Write safe_key_lookup(data, key), catching KeyError as e and formatting a string using e.

5 Debug the Code

Find # TODO 3.5. This function catches the exception as e but never actually uses e in its return value. Fix it.

💼 Scenario

User-friendly error messages

Find # TODO 3.A. Write friendly_parse_error(text), turning a raw exception message into something a non-technical user could read.

💼 Interview Prep

str(e) vs. the exception type name

Find # TODO 3.B. Write explain_str_e_value(), explaining why str(e) is more useful to log than just the exception's type name alone.

Topic 4: Raising Exceptions Deliberately

1 Raising on invalid input

Find # TODO 4.1. Write require_positive(n), raising ValueError with a message if n is not positive.

2 Raising on an out-of-range value

Find # TODO 4.2. Write validate_percentage(value), raising ValueError if value is outside 0-100.

3 Raising on a business rule violation

Find # TODO 4.3. Write withdraw(balance, amount), raising ValueError if amount exceeds balance.

4 Re-raising with added context

Find # TODO 4.4. Write reraise_with_context(func, *args), catching an exception and re-raising it with extra context using raise ... from e.

5 Debug the Code

Find # TODO 4.5. This function raises a bare Exception("...") instead of a specific, meaningful exception type. Fix it.

💼 Scenario

Input validation gate

Find # TODO 4.A. Write validate_signup_age(age) for a signup flow that must raise on invalid ages before any account gets created.

💼 Interview Prep

raise vs. returning None

Find # TODO 4.B. Write explain_raise_vs_none(), explaining when you'd choose to raise an exception instead of silently returning None.

Topic 5: Custom Exception Classes

1 A custom banking exception

Find # TODO 5.1. Define class InsufficientFundsError(Exception) and write withdraw_strict(balance, amount), raising it when funds are short.

2 A custom validation exception

Find # TODO 5.2. Define class InvalidAgeError(Exception) and write register_user(name, age), raising it for an invalid age.

3 Catching your own exception

Find # TODO 5.3. Write custom_error_message(balance, amount), catching InsufficientFundsError as e and returning str(e).

4 Another custom exception

Find # TODO 5.4. Define class NegativeValueError(Exception) and write safe_sqrt(n), raising it for a negative input.

5 Debug the Code

Find # TODO 5.5. This custom exception class forgot to subclass Exception at all, so it can't be raised. Fix it.

💼 Scenario

Domain-specific errors in a banking app

Find # TODO 5.A. Write transfer_funds(balance, amount), using InsufficientFundsError to make the failure self-documenting.

💼 Interview Prep

Why bother with custom exceptions?

Find # TODO 5.B. Write explain_custom_exception_value(), explaining why teams define custom exception classes instead of always raising a generic exception.

Topic 6: Bringing It Together — Exception Handling in Production

1 A structured API response

Find # TODO 6.1. Write safe_api_response(status_code, payload), combining multiple except blocks and a custom exception to return a structured result dict.

2 Validating every input

Find # TODO 6.2. Write process_order(item_price, quantity, discount_percent), raising specific exceptions for each bad case.

3 Retrying a flaky operation

Find # TODO 6.3. Write retry_flaky_operation(func, max_attempts=3), retrying a function that might raise, and returning whether it eventually succeeded.

4 Processing a batch with partial failures

Find # TODO 6.4. Write safe_batch_process(items), collecting successes and failures separately from a list of inputs where some may fail.

5 Debug the Code

Find # TODO 6.5. This function's broad except Exception: silently swallows an unrelated bug instead of surfacing it. Fix it.

💼 Scenario

Production-grade checkout validator

Find # TODO 6.A. Write validate_checkout(cart_total, payment_amount), combining a custom exception, finally logging, and a structured return value.

💼 Interview Prep

Why broad except is a code smell

Find # TODO 6.B. Write explain_broad_except_risk(), explaining why catching Exception too broadly is considered a code smell in production code.

Checking your work Compare your output against solution.py. Your exact wording doesn't need to match — the goal is that your program runs without errors and does what each TODO asks. Remember that any random or "today's date" output will legitimately differ each time you run it.
← Exercises Challenges →