Conditional Execution with if Statements
If every operation in that clause succeeds, execution continues after the complete try-except structure.
When Input Goes Wrong
Programs often receive input that does not match what they expect. Imagine a temperature converter asking for a Fahrenheit temperature. If the user enters hello instead of 98.6, Python cannot convert that text to a floating-point number with float(). Python raises a ValueError, and without error handling the program stops with a crash report.
The try-except Relationship
A try-except block gives Python two possible paths. The try clause contains code that might fail. If every operation in that clause succeeds, execution continues after the complete try-except structure. If an operation raises an error, Python immediately leaves the remaining code in the try clause and runs the except clause. The except clause therefore contains the response your program should use when the expected error occurs.
Tracing Both Execution Paths
In this example, input() is placed before the try clause. The conversion with float(inp) is inside the try clause because converting user input is the operation likely to raise a ValueError. The print operation that depends on a successful conversion is also inside the try clause. If the input is hello, Python fails at float(inp), skips the remaining line in the try clause, and runs the except clause. The user sees Please enter a number rather than an unhandled crash.
What do you think happens?
What will the program display if the user enters hello?
Reveal answer
Please enter a number
float(inp) cannot convert the text hello to a floating-point number, so Python raises ValueError and immediately transfers control to the except clause.
Choosing the Protected Code
A useful rule is to place code that might raise an exception in the try clause. In the temperature example, float(inp) is the main risky operation. The calculation that follows can also remain in the try clause because it depends on the conversion succeeding. If conversion fails, there is no point in attempting the calculation.
Keep the try clause focused. Code that is not at risk of raising an exception in this context does not need to be placed there. The source example identifies input() as an operation that could be placed before the try clause, while the conversion and dependent calculation belong inside it.
Crash Reports and Friendly Messages
| Without try-except | With try-except |
|---|---|
| Invalid conversion raises ValueError | Invalid conversion is handled by the except clause |
| The program stops running | The program responds in a way defined by the programmer |
| The user sees a crash report | The user can see a clear message such as Please enter a number |
| There is no opportunity in that code path to provide a helpful response | The error-handling path provides a user-friendly response |
The two control-flow outcomes described by the temperature-conversion example.
Mistakes to Avoid
Common mistake Putting the risky conversion outside the try clause
What it looks likefahrenheit = float(inp) try: print(fahrenheit)Why it failsIf the input cannot be converted, the error occurs before Python reaches the try clause, so the exception is not handled by that block.
Do this insteadPlace the float(inp) operation inside the try clause.
Common mistake Expecting the except clause to run every time
What it looks liketry: fahrenheit = float(inp) except ValueError: print("Please enter a number")Why it failsThe except clause runs only when an error occurs in the try clause.
Do this insteadTreat except as the error path, not as a second block that always runs.
Common mistake Continuing with dependent work after conversion fails
What it looks liketry: fahrenheit = float(inp) calculation() except ValueError: print("Please enter a number")Why it failsWhen
float(inp)raisesValueError, Python immediately jumps to the except clause and does not execute the remaining lines in the try clause.Do this insteadKeep calculations that depend on a successful conversion in the try clause so they are skipped when conversion fails.
Common mistake Replacing a clear response with an unhelpful crash
What it looks likeA program exposes the error report instead of displaying a message for invalid input.
Why it failsThe user receives a poor experience and the program stops without a response designed by the programmer.
Do this insteadUse the except clause to provide a clear message such as Please enter a number.
Practice the Control Flow
Write a short Python program that reads user input, attempts to convert it with float(), and prints Please enter a number if the conversion raises ValueError. Decide which line belongs before the try clause and which lines belong inside it.
Hints
- The
input()call can be placed before the try clause. - The
float()call belongs in the try clause because non-numeric input can raiseValueError. - The friendly response belongs in the except clause.
- 1Identify the operation that might fail.
- 2Place that operation in the try clause.
- 3Place the response for the expected error in the except clause.
- 4Trace what happens when the operation succeeds.
- 5Trace what happens when the operation raises an exception.
Key Takeaways
- The try clause contains code that might raise an exception.
- The except clause runs only when an error occurs in the try clause.
- When
float()receives non-numeric user input, it can raiseValueError. - An error can move control directly from the failing operation to a user-friendly response.
- Focused try-except blocks make programs more robust and improve the user experience.