Concepts / Understanding Exceptions and Error Messages

Understanding Exceptions and Error Messages

try-except blocks allow programs to catch and handle errors gracefully instead of crashing when unexpected situations occur.

  • Programming

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()?

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

enterattempt conversionyescontinueno: ValueErrorUser inputtext valuefloat(inp)try clauseConversion succeeds?Celsius calculationtry clausePrint resulttry clauseError messageexcept clause
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.

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

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.

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

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

Continue only after success: Perform the conversion to Celsius and print the result only if the Fahrenheit conversion succeeds.

Handle failure: If float() raises a ValueError, 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.

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

unhandled conversion failurehandled by exceptInvalid inputhelloValueErrorprogram stopsInvalid inputhelloPlease enter a numberexcept response
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

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

  • Putting the risky conversion outside the try clause

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

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

  • Expecting the calculation to run after conversion fails

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

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

  • Using a confusing response instead of a user-friendly message

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

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

  • Assuming the except clause always runs

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

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

Key Takeaways

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