Python practice: Defensive Error Handling with try / except

Chapter 15 · 8 questions · included in full access

  1. Question 1 · easy

    Handle zero division safely

    Define safe_div(a, b): return a / b inside try, catch ZeroDivisionError and return 0.0. Call with 100, 0 and print:

    Solve it in your browser
  2. Question 2 · easy

    Safe integer parsing with fallback

    Define parse_int(text): return int(text) in try, catch (ValueError, TypeError) and return 0. Call with "N/A" and print:

    Solve it in your browser
  3. Question 3 · easy

    Handle missing dictionary key

    Given rates = {"North": 0.12}, define get_rate(region): in try return rates[region], catch KeyError and return 0.05. Call with "East" and print:

    Solve it in your browser
  4. Question 4 · easy

    Execute else block on clean run

    Write a function check_amount(amt): in try convert val = float(amt), in else print f"Verified: {val}". Call with "150.5":

    Solve it in your browser
  5. Question 5 · easy

    Guaranteed execution with finally

    Write code: in try print "Processing", in finally print "Cleanup Done". Ensure both lines execute:

    Solve it in your browser
  6. Question 6 · medium

    Raise custom ValueError on negative price

    Define validate_price(p): if p < 0, raise ValueError("Price cannot be negative"), otherwise return p. Call inside try with -10, catch ValueError as e and print str(e):

    Solve it in your browser
  7. Question 7 · medium

    Validate discount range with raise

    Define set_margin(m): if not (0.0 <= m <= 1.0), raise ValueError("Margin must be between 0 and 1"). Test inside try with 1.5, catch ValueError as e and print str(e):

    Solve it in your browser
  8. Question 8 · medium

    Batch row processor with error skipping

    Given raw_rows = ["100", "bad", "250", "missing", "400"], iterate through rows. In try add int(r) to total = 0, catch ValueError and continue. Print total:

    Solve it in your browser

These questions are part of full access.

The first chapters of every track are free. Full access is a one-time payment.

See pricing