Conditional Execution with if Statements
try-except blocks allow programs to catch and handle errors gracefully instead of crashing when unexpected situations occur.
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
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 |
Mistakes to Avoid
Putting the risky conversion outside the try clause
If the input cannot be converted, the error occurs before Python reaches the try clause, so the exception is not handled by that block.
Fix:
Place the float(inp) operation inside the try clause.Expecting the except clause to run every time
The except clause runs only when an error occurs in the try clause.
Fix:
Treat except as the error path, not as a second block that always runs.Continuing with dependent work after conversion fails
When float(inp) raises ValueError, Python immediately jumps to the except clause and does not execute the remaining lines in the try clause.
Fix:
Keep calculations that depend on a successful conversion in the try clause so they are skipped when conversion fails.Replacing a clear response with an unhelpful crash
The user receives a poor experience and the program stops without a response designed by the programmer.
Fix:
Use 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 raise ValueError.
- The friendly response belongs in the except clause.
- Identify the operation that might fail.
- Place that operation in the try clause.
- Place the response for the expected error in the except clause.
- Trace what happens when the operation succeeds.
- Trace 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 raise ValueError.
- 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.