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.
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
- Statements in try run until one raises an exception; the rest of try is skipped.
- Python checks the except clauses in order and runs the first one whose type matches.
- If nothing was raised, the else block runs instead.
- 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.
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.
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()?
Reveal 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.
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.
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
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.
- 1Receive input
Store the user's response as text before attempting the conversion.
- 2Protect the risky operation
Place the
float()conversion in the try clause because non-numeric input can cause aValueError. - 3Continue only after success
Perform the conversion to Celsius and print the result only if the Fahrenheit conversion succeeds.
- 4Handle failure
If
float()raises aValueError, skip the remaining try statements and display a clear instruction instead of allowing the program to crash.
Valid input follows the conversion-and-print path. Invalid input follows the except path and displays Please enter a number.
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 numberHandled and Unhandled Execution
| Situation | Program behavior | User experience |
|---|---|---|
| Invalid input without try-except | Python raises a ValueError and the program stops | The user sees a crash report and cannot receive a planned instruction |
| Invalid input with try-except | Python jumps to the except clause and skips the remaining try statements | The program displays a clear message chosen by the programmer |
| Valid input with try-except | The try statements complete and the except clause is skipped | The 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 likefahrenheit = float(inp) try: celsius = (fahrenheit - 32) * 5 / 9Why it failsIf
float(inp)raises aValueError, execution fails before Python reaches the try clause.Do this insteadPlace 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 likeThe input is hello, but the program is expected to calculate Celsius anyway.
Why it failsPython immediately jumps to the except clause when the conversion fails, so later statements in the try clause are skipped.
Do this insteadTreat 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 likeThe program exposes only a cryptic crash report to the person entering the temperature.
Why it failsThe user is not told what kind of input is expected.
Do this insteadUse 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 likeThe program uses try-except, so the error message is expected even when the input is numeric.
Why it failsThe except clause runs only when an error occurs in the try clause.
Do this insteadRemember that successful try statements skip the except response.
Practice the Control Flow
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.
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
- 1The try clause contains code that might fail.
- 2The except clause runs only when an error occurs in the try clause.
- 3When an error occurs, Python skips the remaining try statements and moves to the except clause.
- 4Type conversions such as
float()are common places to use try-except when processing user input. - 5Friendly 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.