Concepts / Exception Handling Fundamentals

Exception Handling Fundamentals

If non-numeric input causes an exception, control moves to the except block, where the program can handle the invalid input.

  • Programming
Interactive lab

Try it: try / except / else / finally

How an exception jumps out of a try block to the first matching except clause, when else runs, and why finally always runs.

How it works

  1. Statements in try run until one raises an exception; the rest of try is skipped.
  2. Python checks the except clauses in order and runs the first one whose type matches.
  3. If nothing was raised, the else block runs instead.
  4. finally runs in every case.

Default run (9 steps): Call safe_divide('4'). … Return 25.0. Output was: Worked: 25.0 / Done.

Simplified: One fixed function; int() and / are modelled exactly (including how Python prints floats), but nothing is executed as Python.

Educational simulation

Loading the simulation…

Interactive lab

Try it: Validate Input Before Processing

How a program reads untrusted text with input() and checks it in order (empty line, conversion with try / except, allowed range) before it computes anything, re-prompting after each rejected line. Switch a check off, or run the range check before converting, to see which bad input slips through or crashes the program.

How it works

  1. input() always returns a str, even when the user types digits.
  2. Check 1: an empty line (line.strip() == "") is rejected first; the loop prints a message and continue goes back to input().
  3. Check 2: float(line) / int(line) inside try; a non-numeric line raises ValueError and the except block recovers instead of crashing.
  4. Check 3: a converted number outside the allowed range is still invalid and is rejected (the range check must come after the conversion: comparing the str itself raises TypeError).
  5. The first line that passes every check breaks out of the loop and is processed: overtime pay (1.5x only for hours above 40), ordered grade bands, or a ticket total.

Default run (21 steps): The overtime pay program is ready. 4 input lines are queued for input(). … print shows Pay: 475.0.

Simplified: Three fixed programs (you change the input lines and switch the checks, never the code); the lab implements their Python semantics itself and nothing is executed as Python. Every combination was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type, one per call (the prompt is not printed), and raises EOFError when they run out. Input is printable ASCII only.

Educational simulation

Loading the simulation…

Three Control-Flow Decisions

Many beginner programs do more than calculate a single result. They choose between different paths. An overtime program changes its calculation when hours cross 40. An input program must respond differently when a user enters a number or non-numeric text. A grading program checks several score ranges before selecting an outcome. These problems use the same central skill: designing control flow so that each possible input reaches the correct path.

Key point

A reliable conditional program does not only handle the expected input. It also handles threshold values, invalid values, and values that fall outside the permitted range.

Crossing the Overtime Threshold

The overtime calculation has two paths. When hours worked are 40 or less, the calculation uses regular pay for all hours. When hours worked are greater than 40, only the hours above 40 receive the 1.5x multiplier. The regular hours do not receive the multiplier. The important state change is therefore not simply that the total number of hours is large; it is that the program separates regular hours from overtime hours after the 40-hour threshold is crossed.

Hours workedMore than 40?Regular payAll hours use regular rateOvertime payOnly overtime hours use1.5xSeparate hours40 regular and remainingovertimeNoYesApply 1.5x to overtime hours
How does the calculation change when hours worked cross the 40-hour threshold, and how is the 1.5x multiplier applied only to the overtime hours?
Worked example

A 45-Hour Workweek

Determine which hours receive the 1.5x multiplier when a worker records 45 hours.

  1. 1
    Check the threshold

    45 is greater than 40, so the overtime path is selected.

  2. 2
    Separate the hours

    The first 40 hours remain regular hours. The hours above 40 are overtime hours, giving 5 overtime hours.

  3. 3
    Apply the multiplier

    Apply the 1.5x multiplier only to the 5 overtime hours. Do not multiply the first 40 hours by 1.5.

Result

The calculation uses regular pay for 40 hours and the 1.5x rate for 5 overtime hours.

Recovering from Bad Input

User input can fail before the main calculation begins. If a program expects a number but receives non-numeric text, try and except can catch that problem and respond gracefully instead of allowing the program to crash. The try block contains the operation that may fail. If non-numeric input causes an exception, control moves to the except block, where the program can handle the invalid input.

User inputtry blockAttempt numeric operationNumeric inputContinue with calculationexcept blockRespond gracefullyNon-numeric inputException occursConversion succeedsConversion failsControl moves to handler
What happens to control flow when the user enters non-numeric data, and how does execution move from the try block to the except block?
Worked example

Two Input Paths

Predict the control-flow path for numeric input and for text entered where a number is expected.

  1. 1
    Numeric input

    The numeric operation in the try block succeeds, so execution can continue with the result.

  2. 2
    Non-numeric input

    The numeric operation cannot process the text, so an exception occurs and control moves to the except block.

  3. 3
    Graceful response

    The except block handles the invalid input rather than allowing the program to crash.

Result

The try path handles valid numeric input, while the except path handles non-numeric input.

Routing Scores Through Ranges

A grading program can combine range validation with multiple conditional branches. First, the program needs to distinguish valid scores from out-of-range values. For a valid score, an if, elif, elif, else chain checks thresholds in order and routes the score to the matching outcome. If the score is invalid, the program should identify it as invalid rather than assigning it a grade.

ScoreValid range?Invalid valueDo not assign a gradeGrade outcomeMatching branchCheck thresholdsif, elif, elif, elseNoYesFirst matching condition
How does a score move through range checks and multi-branch conditions to produce the correct grade or identify an invalid value?
Worked example

Boundary-Oriented Grade Testing

Plan tests for a grading program whose threshold boundaries include 0.9, 0.8, 0.7, and 0.6.

  1. 1
    Test each boundary

    Run the program with scores exactly equal to 0.9, 0.8, 0.7, and 0.6 to verify how the conditional chain treats each threshold.

  2. 2
    Test values between boundaries

    Use scores between the listed thresholds to verify that each interval reaches the intended branch.

  3. 3
    Test invalid values

    Use 1.5 and -0.1 to verify that out-of-range scores are identified as invalid.

Result

The test set checks threshold inclusion, values between thresholds, and values outside the valid range.

Tracing the Selected Branch

When the result is unexpected, identify which conditional branch actually ran. Add temporary print statements immediately after conditions or inside their branches. In the overtime problem, inspect the hours value and log whether the regular-pay path or overtime path was selected. In the grading problem, inspect the score and log which threshold matched. For exception handling, test both the try path and the except path so you can see which block executed.

  • Common mistake

    Applying the 1.5x multiplier to every hour when the total exceeds 40.

    What it looks like

    Treating 45 hours as 45 overtime hours.

    Why it fails

    The multiplier applies only to hours above 40.

    Do this instead

    Keep the first 40 hours on the regular-pay path and apply 1.5x only to the remaining hours.

  • Common mistake

    Treating exactly 40 hours as overtime.

    What it looks like

    Sending 40 hours into the overtime branch.

    Why it fails

    Overtime applies to hours above 40, not to the threshold itself.

    Do this instead

    Test the exact boundary and keep 40 hours on the regular-pay path.

  • Common mistake

    Handling only valid numeric input.

    What it looks like

    Allowing a numeric conversion attempt to proceed without a handler when the user enters text.

    Why it fails

    Non-numeric input can cause the program to fail instead of responding gracefully.

    Do this instead

    Use try and except around the operation that may receive non-numeric input.

  • Common mistake

    Assigning a grade before checking whether a score is in range.

    What it looks like

    Processing 1.5 or -0.1 as though each were a valid score.

    Why it fails

    Out-of-range values should be identified as invalid.

    Do this instead

    Perform range validation before routing valid scores through the grade branches.

  • Common mistake

    Testing only ordinary values.

    What it looks like

    Testing overtime with one value greater than 40 but never testing less than 40 or exactly 40.

    Why it fails

    A conditional can appear correct while failing at a boundary or edge case.

    Do this instead

    Test boundary values, values between thresholds, invalid values, and intentionally bad input.

ScenarioTest inputExpected path to verify
Regular overtime calculationHours less than 40Regular-pay path
Threshold calculationExactly 40 hoursRegular-pay path
Overtime calculationHours greater than 40Separate regular and overtime hours
Input handlingValid numeric inputtry path
Input handlingNon-numeric textexcept path
Grade validation1.5 or -0.1Invalid-value path
Grade thresholds0.9, 0.8, 0.7, and 0.6Matching threshold branch

A compact test plan for the three conditional patterns

Practice the Three Patterns

MEDIUM

Design the control flow for a small program that first handles a numeric input, then validates its range, and finally routes it through multiple outcomes. Include a separate branch for invalid input. Before running the program, write down the expected path for each of these cases: a valid value in the middle of the range, a value exactly on a boundary, a value outside the range, and non-numeric text.

Hints
  • Separate non-numeric input handling from numeric range validation.
  • Check the range before assigning an outcome.
  • Use boundary tests rather than only ordinary values.
  • Trace which branch executes for every test case.
EASY

For an overtime calculation, predict the path for hours less than 40, exactly 40, and greater than 40. State which hours receive the 1.5x multiplier in each case, then test the program repeatedly with those inputs.

Hints
  • The overtime path begins only above 40 hours.
  • Exactly 40 is a boundary case.
  • When the overtime path is selected, separate regular hours from hours above 40.

Reliable Conditional Programs

  1. 1
    Conditional execution becomes reliable when every important input category has a deliberate path. For overtime, compare hours with 40 and apply 1.5x only to the hours above the threshold. For non-numeric input, place the risky numeric operation in try and handle failure in except. For grading, validate the score before using ordered if and elif branches to select an outcome. Finally, test normal values, boundaries, edge cases, invalid ranges, and intentionally bad input so that the actual control flow matches the intended design.

Key Takeaways

  • Overtime logic branches at 40 hours: regular hours use regular pay, while only hours above 40 receive the 1.5x multiplier.
  • try and except provide separate control-flow paths for successful numeric input and non-numeric input that needs graceful handling.
  • Range validation should occur before a score is assigned to a grade outcome.
  • Ordered if and elif branches route valid scores to the matching threshold outcome.
  • Boundary values, edge cases, out-of-range values, and intentionally bad input are essential tests for conditional programs.

Related concepts

More concepts starting with E