Concepts / Understanding Exceptions and Error Messages

Understanding Exceptions and Error Messages

An exception is an error that occurs while a program is running. Exception handling lets you decide how the program should respond instead of allowing the program to crash.

  • 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…

When Input Breaks a Program

A program can appear to work correctly until a user provides an unexpected value. Imagine a temperature converter that asks for a Fahrenheit temperature, converts the response to a number, calculates Celsius, and prints the result. If the user enters hello instead of 98.6, the conversion cannot succeed. Python raises a ValueError, displays an error message, and stops the program.

Key point

An exception is an error that occurs while a program is running. Exception handling lets you decide how the program should respond instead of allowing the program to crash.

What do you think happens?

A temperature converter has already received the text hello. What happens when it tries to convert that text with float()?

  • The conversion produces a numeric result

  • Python raises a ValueError and the program stops if the error is unhandled

  • Python silently ignores the input

  • The calculation continues using hello

Reveal answer
Answer:

Python raises a ValueError and the program stops if the error is unhandled

float() cannot convert a string containing non-numeric characters into a floating-point number. Without exception handling, the program does not continue to the calculation or output.

The Try-Except Control Path

A try-except block gives Python two possible paths. Python begins with the statements in the try clause. If those statements finish without an error, the except clause is not run. If an error occurs in the try clause, Python immediately leaves the remaining statements in that clause and moves to the except clause. This means statements after the failing line in the try clause are skipped.

User inputtext valuefloat(inp)try clauseConversion succeeds?Celsius calculationtry clausePrint resulttry clauseError messageexcept clauseenterattempt conversionyescontinueno: ValueError
What happens when a conversion fails inside the try clause, and which statements run afterward?

The important control-flow change is the jump from the failing operation to the except clause. With invalid input, the calculation and result-printing statements do not run. With valid input, the calculation and result printing run, while the except clause is skipped.

Assigning Code to Each Clause

Put code in the try clause when that code might raise the exception you want to handle. In the temperature converter, float(inp) is a clear risk because user input may contain non-numeric characters. The calculation can also remain in the try clause because it depends on a successful conversion. Put the response to the failure in the except clause, such as displaying a friendly instruction to the user.

inp = input(...)gets user texttry:begin protected operationsfloat(inp)may raise ValueErrorcalculationdepends on conversionexcept ValueError:handles conversion failurefriendly messagetell the user what to enterthenprotectif successfulif ValueErrordisplay
Which operations might fail, and which statement handles that failure?
Best practice

Keep the try clause focused on operations that might fail. The input() call itself is unlikely to raise an exception in this context, so it can be placed before the try clause. The conversion and dependent calculation belong together because the calculation has no useful purpose if conversion fails.

A Friendly Temperature Converter

Worked example

Handling Invalid Fahrenheit Input

Design the control flow for a program that converts Fahrenheit to Celsius and responds clearly when the user enters non-numeric text.

  1. 1
    Receive input

    Store the user's response as text before attempting the conversion.

  2. 2
    Protect the risky operation

    Place the float() conversion in the try clause because non-numeric input can cause a ValueError.

  3. 3
    Continue only after success

    Perform the conversion to Celsius and print the result only if the Fahrenheit conversion succeeds.

  4. 4
    Handle failure

    If float() raises a ValueError, skip the remaining try statements and display a clear instruction instead of allowing the program to crash.

Result

Valid input follows the conversion-and-print path. Invalid input follows the except path and displays Please enter a number.

python
Output
If the user enters hello, the float(inp) operation raises a ValueError. The calculation and first print statement are skipped, and the program displays:
Please enter a number

Handled and Unhandled Execution

Invalid inputhelloValueErrorprogram stopsInvalid inputhelloPlease enter a numberexcept responseunhandled conversion failurehandled by except
How does execution differ when the same invalid input is handled compared with when it is left unhandled?
SituationProgram behaviorUser experience
Invalid input without try-exceptPython raises a ValueError and the program stopsThe user sees a crash report and cannot receive a planned instruction
Invalid input with try-exceptPython jumps to the except clause and skips the remaining try statementsThe program displays a clear message chosen by the programmer
Valid input with try-exceptThe try statements complete and the except clause is skippedThe calculation and result are displayed

The same conversion task can have very different control flow depending on whether the exception is handled.

Exception handling changes the program's response, not the fact that the input was invalid. The conversion still cannot use hello as a number. The difference is that the program recognizes the failure and follows a deliberate response path. This improves robustness and gives the user a clearer experience.

Mistakes Beginners Make

  • Common mistake

    Putting the risky conversion outside the try clause

    What it looks like
    fahrenheit = float(inp)
    try:
        celsius = (fahrenheit - 32) * 5 / 9
    Why it fails

    If float(inp) raises a ValueError, execution fails before Python reaches the try clause.

    Do this instead

    Place the conversion inside the try clause so the except clause can handle its failure.

  • Common mistake

    Expecting the calculation to run after conversion fails

    What it looks like

    The input is hello, but the program is expected to calculate Celsius anyway.

    Why it fails

    Python immediately jumps to the except clause when the conversion fails, so later statements in the try clause are skipped.

    Do this instead

    Treat the calculation as dependent on successful conversion and keep it in the try clause.

  • Common mistake

    Using a confusing response instead of a user-friendly message

    What it looks like

    The program exposes only a cryptic crash report to the person entering the temperature.

    Why it fails

    The user is not told what kind of input is expected.

    Do this instead

    Use the except clause to display a clear message such as Please enter a number.

  • Common mistake

    Assuming the except clause always runs

    What it looks like

    The program uses try-except, so the error message is expected even when the input is numeric.

    Why it fails

    The except clause runs only when an error occurs in the try clause.

    Do this instead

    Remember that successful try statements skip the except response.

Practice the Control Flow

EASY

A program asks for a Fahrenheit temperature and uses a try-except block. Explain what happens for the input 98.6 and for the input hello. Identify the operation that can raise ValueError, name the statements skipped after the failure, and write a friendly message for the except clause.

Hints
  • Look for the operation that converts user text into a floating-point number.
  • When that operation fails, execution jumps immediately to the except clause.
  • The calculation should not run unless conversion succeeds.
MEDIUM

Review a small input-handling task and decide which lines belong before the try clause, which belong inside it, and which belong inside except. Keep the try clause focused on operations that might fail.

Hints
  • The input() call can be placed before the try clause in this context.
  • Type conversion and dependent calculation are protected operations.
  • The except clause should communicate what the user needs to do differently.

Key Takeaways

  1. 1
    The try clause contains code that might fail.
  2. 2
    The except clause runs only when an error occurs in the try clause.
  3. 3
    When an error occurs, Python skips the remaining try statements and moves to the except clause.
  4. 4
    Type conversions such as float() are common places to use try-except when processing user input.
  5. 5
    Friendly error messages make programs more robust and easier for users to understand.

At a glance

  • Use try-except to handle runtime errors instead of allowing the program to crash.
  • Place operations that might fail, such as float() conversion, in the try clause.
  • When an exception occurs, Python skips the rest of the try clause and runs the matching except clause.
  • Use the except clause to give users a clear, friendly response.
  • Keep protected code focused on risky operations and dependent calculations.

Related concepts

More concepts starting with U