Common Exception Types in Python
The Python interpreter recovers from errors and returns a prompt; a script terminates immediately with a traceback.
One Error, Two Outcomes
The same error can feel very different depending on how Python is running. When you enter a command directly into the interactive interpreter, Python reports the error and gives you another prompt. You can then enter a different command. When the same kind of error occurs in a script, Python stops the script and prints a traceback. The difference is not that the error has become less serious in the interpreter; the surrounding execution environment responds differently.
Interactive Recovery
The interactive interpreter processes commands one at a time. If one command raises an exception, Python displays an error message and then shows a new prompt. That prompt means the interpreter is ready to receive another command. The failed command does not prevent you from trying again with different input.
Suppose an interactive user attempts a conversion with int('hello'). Python reports a ValueError because the string does not represent a valid integer. The user then receives a new prompt and can try a different value. The exception is still real, but the interactive interpreter has not ended.
ValueError in Conversion
A ValueError occurs when a function receives an argument of the correct type but an inappropriate value. During type conversion, this commonly happens when int() or float() receives a string containing letters or other non-numeric characters.
The important distinction is between type and value. The conversion function receives a string, which is an acceptable kind of argument for conversion, but the contents of that string are not suitable for the requested numeric result. Therefore Python raises ValueError rather than completing the conversion.
Tracing a Temperature Conversion
A script reads a Fahrenheit temperature, converts the input with float(), calculates Celsius, and prints the result. What happens when the input is fred?
Read input: The script stores the entered text in its input variable.
Convert input: The statement fahr = float(inp) asks Python to convert the string fred to a floating-point number.
Raise ValueError: The string fred is not a valid value for float(), so Python raises ValueError.
Stop execution: The Celsius calculation and the print statement are not executed because the script terminates at the failed conversion.
The invalid value causes a ValueError before the temperature calculation can run.
Reading a Traceback
A traceback is a detailed report of an exception in a script. It shows the sequence of calls that led to the failure and narrows that sequence down to the line where the exception occurred. This makes the traceback a roadmap for locating the source of the problem.
| Traceback detail | What it tells you |
|---|---|
| Traceback (most recent call last) | The following lines describe the chain of calls leading to the exception. |
| File fahren.py, line 2, in <module> | The exception occurred at the top level of fahren.py on line 2. |
| fahr = float(inp) | This is the statement where the failure occurred. |
| ValueError: could not convert string to float: 'fred' | The exception type and its specific explanation. |
Parts of the source traceback described in the lesson.
Mistakes Beginners Make
Assuming that a new interpreter prompt means the command succeeded
The new prompt indicates that the interactive interpreter is ready for another command; it does not undo the exception or make the failed command successful.
Fix:
Treat the error message as evidence that the command failed, then use the new prompt to try a corrected command.Expecting a script to continue after a ValueError
An unhandled exception causes the script to stop immediately, so later statements are not executed.
Fix:
Use the traceback to find the failing statement and recognize that error handling with try and except is needed for graceful responses.Calling every conversion problem a type problem
The argument is a string, but its contents are not a valid floating-point value. This situation produces ValueError.
Fix:
Ask whether the argument has an appropriate type and whether its value is valid for the requested conversion.Looking only at the final line of a traceback
The earlier traceback lines locate where the failure occurred and show the call sequence that led to it.
Fix:
Read the exception type together with the file name, line number, displayed statement, and explanatory message.
Practice the Distinction
Imagine that a user supplies fred where a program expects a Fahrenheit temperature. Compare what you would observe if the conversion command were entered directly into the interactive interpreter with what you would observe if the same conversion appeared in a script before a calculation and a print statement.
Hints
- Identify the exception type caused by converting fred with float().
- For the interpreter, identify what appears after the error.
- For the script, identify whether the later calculation and print statement execute.
- Use the traceback details to identify the file, line, statement, and invalid value.
Checking Your Reasoning
An interactive conversion raises ValueError. A new prompt appears. The same conversion in a script produces a traceback. What is the key difference?
Same exception: In both settings, the invalid value causes ValueError.
Interactive response: The interpreter reports the error and returns a prompt, allowing another command.
Script response: The script prints a traceback and terminates, so later statements do not execute.
The exception is the same, but the execution environment determines whether you receive another prompt or lose the rest of the script's execution.
Why Error Handling Matters
Program termination explains why robust programs need error handling. Users may enter invalid data, and other operations may fail. If an exception is not handled, Python stops the script and reports the failure with a traceback. The next step beyond recognizing this behavior is learning to catch exceptions with try and except blocks so a program can respond gracefully instead of crashing.
Key Takeaways
- The interactive interpreter reports an exception and returns a new prompt, while a script stops and prints a traceback.
- ValueError occurs when a function receives an argument of the correct type but an inappropriate value, such as a non-numeric string passed to int() or float().
- A traceback identifies the exception, the call sequence, the file, the line, the failing statement, and the specific error message.
- When a script terminates because of an unhandled exception, statements after the failure do not execute.
- Understanding termination provides the motivation for handling exceptions with try and except blocks.