Python practice: Defensive Error Handling with try / except
Chapter 15 · 8 questions · included in full access
Question 1 · easy
Handle zero division safely
Solve it in your browserDefine
safe_div(a, b): returna / binsidetry, catchZeroDivisionErrorand return0.0. Call with100, 0and print:Question 2 · easy
Safe integer parsing with fallback
Solve it in your browserDefine
parse_int(text): returnint(text)intry, catch(ValueError, TypeError)and return0. Call with"N/A"and print:Question 3 · easy
Handle missing dictionary key
Solve it in your browserGiven
rates = {"North": 0.12}, defineget_rate(region): intryreturnrates[region], catchKeyErrorand return0.05. Call with"East"and print:Question 4 · easy
Execute else block on clean run
Solve it in your browserWrite a function
check_amount(amt): intryconvertval = float(amt), inelseprintf"Verified: {val}". Call with"150.5":Question 5 · easy
Guaranteed execution with finally
Solve it in your browserWrite code: in
tryprint"Processing", infinallyprint"Cleanup Done". Ensure both lines execute:Question 6 · medium
Raise custom ValueError on negative price
Solve it in your browserDefine
validate_price(p): ifp < 0,raise ValueError("Price cannot be negative"), otherwise returnp. Call insidetrywith-10, catchValueError as eand printstr(e):Question 7 · medium
Validate discount range with raise
Solve it in your browserDefine
set_margin(m): if not(0.0 <= m <= 1.0),raise ValueError("Margin must be between 0 and 1"). Test insidetrywith1.5, catchValueError as eand printstr(e):Question 8 · medium
Batch row processor with error skipping
Solve it in your browserGiven
raw_rows = ["100", "bad", "250", "missing", "400"], iterate through rows. Intryaddint(r)tototal = 0, catchValueErrorand continue. Printtotal:
These questions are part of full access.
The first chapters of every track are free. Full access is a one-time payment.
See pricing