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.
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.
b may be 0; a and b may be negative.
safe_divide(10, 2) → 5.0safe_divide(10, 0) → Nonesafe_divide(-9, 3) → -3.0
Show Solution
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.
text is always a string; it may or may not represent a valid integer.
safe_int_parse("42", None) → 42safe_int_parse("abc", None) → Nonesafe_int_parse("-7", None) → -7
Show Solution
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.
index may be negative (Python indexing) or completely out of bounds; items may be empty.
safe_list_index([1, 2, 3], 0) → 1safe_list_index([1, 2, 3], 10) → "out of range"safe_list_index([1, 2, 3], -1) → 3
Show Solution
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".
a or b may be a string instead of a number, which raises TypeError when dividing.
which_error(10, 0) → "ZeroDivisionError"which_error(10, "x") → "TypeError"which_error(10, 2) → "ok:5.0"
Show Solution
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.
values may be empty (return [0, 0]); any pair may divide by zero.
divide_and_count([[10, 2], [5, 0], [8, 4]]) → [2, 3]divide_and_count([[1, 0]]) → [0, 1]divide_and_count([]) → [0, 0]
Show Solution
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.
value may be negative or greater than 100; boundary values 0 and 100 are valid.
validate_percentage_safe(50) → Truevalidate_percentage_safe(150) → Falsevalidate_percentage_safe(0) → True
Show Solution
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.
amount may equal balance exactly (that's allowed, not insufficient); values may be floats.
safe_transaction(100, 30) → 70safe_transaction(100, 500) → "not enough funds"safe_transaction(50, 50) → 0
Show Solution
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.
on_date before birth_date.
safe_age_on_date("2000-07-05", "2026-07-05") → 26safe_age_on_date("2000-07-06", "2026-07-05") → 25safe_age_on_date("2026-01-01", "2000-01-01") → -1
Show Solution
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