Concepts / Introduction to Error Handling

Introduction to Error Handling

ValueError is a runtime error that occurs when type conversion fails—for example, when int() tries to convert a string like 'hello' to an integer.

  • Programming

When Conversion Fails

When a program asks for input with input(), Python receives a string. If the program needs to use that response as a number, it can pass the string to int() or float(). The conversion can fail when the characters do not describe a value of the requested type. For example, passing the string "hello" to int() causes Python to raise a ValueError.

A ValueError is a runtime error that occurs when type conversion fails, such as when int() tries to convert a string like "hello" to an integer.

Tracing the Input

receivesint() succeedsreceivesint() failsinput()string"42"valid string42integer"hello"invalid stringValueErrorconversion failure
What changes when a string is passed to int(), and where does the data flow when conversion succeeds or fails?

The conversion function examines the characters in the string. For integer conversion, a string can contain only digits and may optionally begin with a plus or minus sign. If the characters are valid, int() returns a new integer. If any character is invalid, conversion stops and Python raises a ValueError.

Input stringConversion with int()Result
"42"ValidInteger 42
"-7"ValidInteger -7
"hello"InvalidValueError
"3.14"Invalid for integer conversionValueError

The Try and Except Path

A try/except block gives the program two possible paths. The try block contains the code that might raise an error, such as converting user input with int(). If that code succeeds, Python continues after the try/except structure. If a ValueError occurs, Python moves to the except ValueError block and runs its indented handling code instead of allowing the failure to crash the program.

passes stringvalid inputinvalid inputjumps todisplaysUser inputstringtry blockint() conversionInteger resultconversion succeedsValueErrorconversion failsexcept blockhandle failureError messageuser guidance
What happens to program control when int() raises a ValueError, and how does execution move from the try block to the except block?
python

The indented statement inside try is the operation that might fail. The phrase except ValueError identifies the error this handler is prepared to catch. The indented statement inside except runs only when the conversion raises that error.

A Complete User Input Example

Handling a User's Number

Convert a user's response to an integer and show a clear message if the response cannot be converted.

Receive the response: input() provides a string, even when the user types characters that look like a number.

Attempt conversion: Place int() inside the try block because the conversion may raise a ValueError.

Handle failure: Use except ValueError to display a message explaining that the user should enter a whole number.

Valid input produces an integer. Invalid input is handled by the except block instead of causing an unhandled crash.

python
Output
If the user enters 42, the conversion succeeds and the program prints:
You entered 42

If the user enters hello, the conversion raises a ValueError and the program prints:
That input is not a valid whole number.

Graceful Recovery

receiveswithout handlingwith try/exceptprovidesAsking for inputprogram runningInvalid stringconversion failsUnhandled errorundesired resultexcept ValueErrorerror handledClear error messageuser can correct input
How does a program respond after invalid input so it can show an error message instead of crashing?

User input is unpredictable, so conversions of user input should be protected with try/except. A handled ValueError lets the program respond deliberately, such as by asking the user to try again or providing a sensible default behavior. The important change is in the program's response: the failure is handled in the except block rather than being left to crash the program.

Keep the potentially failing conversion inside the try block and put a clear corrective message inside the except ValueError block. Tell the user what kind of input is expected.

Mistakes to Avoid

  • Assuming that input() returns a number when the user types digits.

    If the program needs a number, it must convert the string with int() or float().

    Fix: Pass the input string to the appropriate conversion function.

  • Converting user input without handling ValueError.

    An input such as hello cannot be converted to an integer, so the unhandled error can crash the program.

    Fix: Place the conversion in a try block and catch ValueError in an except block.

  • Treating every string as valid integer input.

    Integer conversion accepts digits and an optional leading plus or minus sign, not arbitrary letters.

    Fix: Handle invalid input with except ValueError and explain the expected format.

  • Giving no useful guidance after a failed conversion.

    The user may not understand how to fix the input.

    Fix: Provide a clear error message describing the expected input.

Practice the Control Flow

EASY

Write a short Python program that asks for a value, attempts to convert it with int(), and prints one message for successful conversion and a different message in except ValueError for failed conversion.

Hints
  • Remember that input() returns a string.
  • Put int() inside the try block.
  • Use except ValueError for the failed conversion path.
  • Make the error message tell the user what kind of input is expected.

What do you think happens?

What happens when the conversion in the try block receives the string "hello"?

  • The string is silently changed into an integer
  • The except ValueError block runs
  • The program always continues through the rest of the try block
Reveal answer

Answer: The except ValueError block runs.

The string contains letters that int() cannot interpret as an integer. Python raises a ValueError, and a matching except ValueError handler takes control.

Key Takeaways

  1. input() provides a string, even when the user types digits.
  2. int() can convert strings containing digits and an optional leading plus or minus sign; invalid content can cause a ValueError.
  3. A ValueError is raised at runtime when the requested type conversion fails.
  4. The try block contains code that might fail, and except ValueError contains the response to that failure.
  5. Handling user-input conversions with try/except and clear messages prevents an unpleasant unhandled crash.

Key Takeaways

  • A ValueError occurs when a conversion such as int() cannot interpret the supplied string as the requested type.
  • Valid integer strings contain digits and may include a leading plus or minus sign; strings with invalid content cause conversion to fail.
  • Use try for the potentially failing conversion and except ValueError for the handling path.
  • User input should be treated as unpredictable, so failed conversions should produce clear guidance rather than an unhandled crash.