🐍 Python for Everyone

← Back to practice bank

Chapter 12 Coding Challenges 50-65 min, auto-graded

Coding Challenges: Exception Handling

8 HackerRank-style challenges, auto-graded right in your browser — no setup required. Write your function in the code box, then click Run Tests to check it against a set of test cases (including edge cases). Stuck? Every challenge has a Show Solution reveal at the bottom. Only uses what Chapters 1-12 have covered so far — everything through decorators, the math and datetime modules, and this chapter's own toolkit: try/except/ else/finally, raise, and custom exception classes that subclass Exception. No file I/O, no other class besides a custom exception, and no import beyond math/datetime.

How grading works Your code runs entirely in your browser using Pyodide (Python compiled to WebAssembly) — nothing is uploaded anywhere. Keep the function name in the stub exactly as given, since the grader calls it by name.
Why every function below returns instead of raising The grader calls your function once per test case and compares its return value to an expected value — it can't "expect an exception" as the right answer. So every challenge here is designed the way production code often is: catch the risky part inside the function, and return a value that describes what happened (a sentinel like None, a status string, a boolean, or a dict) instead of letting the exception escape to the caller.

1 Safe Divide Easy

Write a function safe_divide(a, b) that returns a / b, but catches ZeroDivisionError and returns None instead of crashing when b is 0.

Constraints: b may be 0; a and b may be negative.
Examples:
safe_divide(10, 2) → 5.0
safe_divide(10, 0) → None
safe_divide(-9, 3) → -3.0
challenge_1.py
Show Solution
solution_1.py
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None

2 Safe Integer Parse Easy

Write a function safe_int_parse(text, default) that returns int(text), but catches ValueError and returns default instead when text can't be converted.

Constraints: text is always a string; it may or may not represent a valid integer.
Examples:
safe_int_parse("42", None) → 42
safe_int_parse("abc", None) → None
safe_int_parse("-7", None) → -7
challenge_2.py
Show Solution
solution_2.py
def safe_int_parse(text, default):
    try:
        return int(text)
    except ValueError:
        return default

3 Safe List Index Easy

Write a function safe_list_index(items, index) that returns items[index], but catches IndexError and returns the string "out of range" instead of crashing.

Constraints: index may be negative (Python indexing) or completely out of bounds; items may be empty.
Examples:
safe_list_index([1, 2, 3], 0) → 1
safe_list_index([1, 2, 3], 10) → "out of range"
safe_list_index([1, 2, 3], -1) → 3
challenge_3.py
Show Solution
solution_3.py
def safe_list_index(items, index):
    try:
        return items[index]
    except IndexError:
        return "out of range"

4 Which Error? Easy

Write a function which_error(a, b) that tries to return "ok:" + str(a / b), using separate except blocks: catch ZeroDivisionError and return the string "ZeroDivisionError", and catch TypeError (from dividing a non-number) and return the string "TypeError".

Constraints: a or b may be a string instead of a number, which raises TypeError when dividing.
Examples:
which_error(10, 0) → "ZeroDivisionError"
which_error(10, "x") → "TypeError"
which_error(10, 2) → "ok:5.0"
challenge_4.py
Show Solution
solution_4.py
def which_error(a, b):
    try:
        result = a / b
        return "ok:" + str(result)
    except ZeroDivisionError:
        return "ZeroDivisionError"
    except TypeError:
        return "TypeError"

5 Divide and Count Medium

Write a function divide_and_count(values) where values is a list of [a, b] pairs. For each pair, try a / b inside a try/except ZeroDivisionError/finally: count it as a success only if the division works, but use finally to count it as an "attempt" every single time, success or failure. Return [successes, attempts] as a two-item list — this demonstrates that finally always runs regardless of whether the try succeeded or the except fired.

Constraints: values may be empty (return [0, 0]); any pair may divide by zero.
Examples:
divide_and_count([[10, 2], [5, 0], [8, 4]]) → [2, 3]
divide_and_count([[1, 0]]) → [0, 1]
divide_and_count([]) → [0, 0]
challenge_5.py
Show Solution
solution_5.py
def divide_and_count(values):
    successes = 0
    attempts = 0
    for a, b in values:
        try:
            a / b
            successes += 1
        except ZeroDivisionError:
            pass
        finally:
            attempts += 1
    return [successes, attempts]

6 Validate Percentage (Custom Exception) Medium

Define a custom exception class OutOfRangeError that subclasses Exception. Write a function validate_percentage_safe(value) that raises OutOfRangeError if value is outside 0-100, and otherwise returns True — but catch that OutOfRangeError inside the same function and return False instead of letting it escape, since the grader can only check a return value.

Constraints: value may be negative or greater than 100; boundary values 0 and 100 are valid.
Examples:
validate_percentage_safe(50) → True
validate_percentage_safe(150) → False
validate_percentage_safe(0) → True
challenge_6.py
Show Solution
solution_6.py
class OutOfRangeError(Exception):
    pass


def validate_percentage_safe(value):
    try:
        if value < 0 or value > 100:
            raise OutOfRangeError(f"{value} out of range")
        return True
    except OutOfRangeError:
        return False

7 Safe Transaction (Custom Exception) Medium

Define a custom exception class InsufficientFundsError that subclasses Exception. Write a function safe_transaction(balance, amount) that raises InsufficientFundsError("not enough funds") if amount is greater than balance, and otherwise returns round(balance - amount, 2) — but catch that exception inside the same function with as e and return str(e) instead of letting it escape.

Constraints: amount may equal balance exactly (that's allowed, not insufficient); values may be floats.
Examples:
safe_transaction(100, 30) → 70
safe_transaction(100, 500) → "not enough funds"
safe_transaction(50, 50) → 0
challenge_7.py
Show Solution
solution_7.py
class InsufficientFundsError(Exception):
    pass


def safe_transaction(balance, amount):
    try:
        if amount > balance:
            raise InsufficientFundsError("not enough funds")
        return round(balance - amount, 2)
    except InsufficientFundsError as e:
        return str(e)

8 Safe Age on Date Medium

Write a function safe_age_on_date(birth_date_str, on_date_str) that takes two ISO date strings, converts each with datetime.date.fromisoformat(...), raises ValueError("on_date is before birth_date") if on_date comes before birth_date, and otherwise returns the age in full years on on_date (compute the plain year difference, then subtract 1 if the birthday hasn't happened yet that year by comparing (month, day) tuples). Catch that ValueError inside the function and return -1 instead of letting it escape, since a negative age isn't otherwise possible.

Constraints: dates are always valid calendar dates; test cases include a birthday not yet reached in the target year, a Feb 29 birth date, and on_date before birth_date.
Examples:
safe_age_on_date("2000-07-05", "2026-07-05") → 26
safe_age_on_date("2000-07-06", "2026-07-05") → 25
safe_age_on_date("2026-01-01", "2000-01-01") → -1
challenge_8.py
Show Solution
solution_8.py
import datetime


def safe_age_on_date(birth_date_str, on_date_str):
    try:
        birth = datetime.date.fromisoformat(birth_date_str)
        on_date = datetime.date.fromisoformat(on_date_str)
        if on_date < birth:
            raise ValueError("on_date is before birth_date")
        years = on_date.year - birth.year
        if (on_date.month, on_date.day) < (birth.month, birth.day):
            years -= 1
        return years
    except ValueError:
        return -1
← Practice Bank Interview Questions →