Concepts / Exception Handling Fundamentals

Exception Handling Fundamentals

Overtime pay requires applying a 1.5x multiplier only to hours worked above 40; the calculation path diverges at this threshold.

  • Programming

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.

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.

NoYesApply 1.5x to overtime hoursHours workedMore than 40?Regular payAll hours use regular rateOvertime payOnly overtime hours use1.5xSeparate hours40 regular and remainingovertime
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?

A 45-Hour Workweek

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

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

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

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

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.

Conversion succeedsConversion failsControl moves to handlerUser inputtry blockAttempt numeric operationNumeric inputContinue with calculationexcept blockRespond gracefullyNon-numeric inputException occurs
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?

Two Input Paths

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

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

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

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

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.

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

Boundary-Oriented Grade Testing

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

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.

Test values between boundaries: Use scores between the listed thresholds to verify that each interval reaches the intended branch.

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

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.

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

    The multiplier applies only to hours above 40.

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

  • Treating exactly 40 hours as overtime.

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

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

  • Handling only valid numeric input.

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

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

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

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

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

  • Testing only ordinary values.

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

    Fix: 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. 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.