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
Interactive lab

Try it: try / except / else / finally

How an exception jumps out of a try block to the first matching except clause, when else runs, and why finally always runs.

How it works

  1. Statements in try run until one raises an exception; the rest of try is skipped.
  2. Python checks the except clauses in order and runs the first one whose type matches.
  3. If nothing was raised, the else block runs instead.
  4. finally runs in every case.

Default run (9 steps): Call safe_divide('4'). … Return 25.0. Output was: Worked: 25.0 / Done.

Simplified: One fixed function; int() and / are modelled exactly (including how Python prints floats), but nothing is executed as Python.

Educational simulation

Loading the simulation…

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.

Definition

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

input()string"42"valid string42integer"hello"invalid stringValueErrorconversion failurereceivesint() succeedsreceivesint() fails
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

Examples of strings that can or cannot be converted to integers

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.

User inputstringtry blockint() conversionInteger resultconversion succeedsValueErrorconversion failsexcept blockhandle failureError messageuser guidancepasses stringvalid inputinvalid inputjumps todisplays
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

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

  1. 1
    Receive the response

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

  2. 2
    Attempt conversion

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

  3. 3
    Handle failure

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

Result

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

Asking for inputprogram runningInvalid stringconversion failsUnhandled errorundesired resultexcept ValueErrorerror handledClear error messageuser can correct inputreceiveswithout handlingwith try/exceptprovides
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.

Best practice

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

  • Common mistake

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

    What it looks like

    The user types 42, but input() still provides a string.

    Why it fails

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

    Do this instead

    Pass the input string to the appropriate conversion function.

  • Common mistake

    Converting user input without handling ValueError.

    What it looks like
    number = int(response)
    Why it fails

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

    Do this instead

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

  • Common mistake

    Treating every string as valid integer input.

    What it looks like
    int("hello")
    Why it fails

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

    Do this instead

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

  • Common mistake

    Giving no useful guidance after a failed conversion.

    What it looks like

    The except block does not explain what the user should enter.

    Why it fails

    The user may not understand how to fix the input.

    Do this instead

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

At a glance

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

Related concepts

More concepts starting with I