Concepts / Conditional Execution with if Statements

Conditional Execution with if Statements

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

  • Programming

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.

given toraiseshandled byhellouser inputfloat()conversion attemptValueErrorconversion failsPlease enter a numberhandled response
How does program execution move from an error-producing operation to an error-handling response?

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.

containserror leads tocan producetrystart risky coderisky operationmight raise an errorexceptrespond to an errorfriendly messageruns after an error
Which code belongs in the try clause, which code belongs in the except clause, and how are the two connected?
python

Tracing Both Execution Paths

python

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?

  • A number was entered: hello
  • Please enter a number
  • Nothing; the program always stops before displaying text
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.

runsnoyesthenafter responsetry clausebegin protected codeoperationdoes it raise an error?following codetry completedexcept clauseerror responseprogram continuesafter handling
What happens next when code in the try clause runs successfully versus when it raises an error?

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.

input supplied tosuccessful conversion enablesfailure activatesinput()can be before tryfloat(inp)may raise ValueErrorcalculationdepends on conversionerror messageresponse in except
Why should the try clause contain the risky operation and its dependent work rather than unrelated code?

Crash Reports and Friendly Messages

Without try-exceptWith try-except
Invalid conversion raises ValueErrorInvalid conversion is handled by the except clause
The program stops runningThe program responds in a way defined by the programmer
The user sees a crash reportThe user can see a clear message such as Please enter a number
There is no opportunity in that code path to provide a helpful responseThe error-handling path provides a user-friendly response
without handlingwith handlinginvalid inputhelloinvalid inputhellocrash reportprogram stopsPlease enter a numberdefined response
What does the user see when an exception occurs, and how does that differ from an unhandled program crash?

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

EASY

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.
  1. Identify the operation that might fail.
  2. Place that operation in the try clause.
  3. Place the response for the expected error in the except clause.
  4. Trace what happens when the operation succeeds.
  5. 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.