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.
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
- Statements in try run until one raises an exception; the rest of try is skipped.
- Python checks the except clauses in order and runs the first one whose type matches.
- If nothing was raised, the else block runs instead.
- 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.
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.
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
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 string | Conversion with int() | Result |
|---|---|---|
| "42" | Valid | Integer 42 |
| "-7" | Valid | Integer -7 |
| "hello" | Invalid | ValueError |
| "3.14" | Invalid for integer conversion | ValueError |
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.
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.
- 1Receive the response
input()provides a string, even when the user types characters that look like a number. - 2Attempt conversion
Place
int()inside the try block because the conversion may raise aValueError. - 3Handle failure
Use except
ValueErrorto 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.
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
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
Common mistake Assuming that input() returns a number when the user types digits.
What it looks likeThe user types 42, but input() still provides a string.
Why it failsIf the program needs a number, it must convert the string with
int()orfloat().Do this insteadPass the input string to the appropriate conversion function.
Common mistake Converting user input without handling ValueError.
What it looks likenumber = int(response)Why it failsAn input such as hello cannot be converted to an integer, so the unhandled error can crash the program.
Do this insteadPlace 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 likeint("hello")Why it failsInteger conversion accepts digits and an optional leading plus or minus sign, not arbitrary letters.
Do this insteadHandle invalid input with except ValueError and explain the expected format.
Common mistake Giving no useful guidance after a failed conversion.
What it looks likeThe except block does not explain what the user should enter.
Why it failsThe user may not understand how to fix the input.
Do this insteadProvide a clear error message describing the expected input.
Practice the Control Flow
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
ValueErrorfor 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"?
Reveal 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 aValueError. - 3A
ValueErroris raised at runtime when the requested type conversion fails. - 4The try block contains code that might fail, and except
ValueErrorcontains the response to that failure. - 5Handling user-input conversions with try/except and clear messages prevents an unpleasant unhandled crash.
At a glance
- A
ValueErroroccurs when a conversion such asint()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
ValueErrorfor the handling path. - User input should be treated as unpredictable, so failed conversions should produce clear guidance rather than an unhandled crash.