Common Exception Types in Python
The Python interpreter recovers from errors and returns a prompt; a script terminates immediately with a traceback.
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…
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?
- 1Read input
The script stores the entered text in its input variable.
- 2Convert input
The statement fahr =
float(inp)asks Python to convert the string fred to a floating-point number. - 3Raise ValueError
The string fred is not a valid value for
float(), so Python raisesValueError. - 4Stop 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
Common mistake Assuming that a new interpreter prompt means the command succeeded
What it looks likeAn error message appears, followed by another prompt.
Why it failsThe new prompt indicates that the interactive interpreter is ready for another command; it does not undo the exception or make the failed command successful.
Do this insteadTreat the error message as evidence that the command failed, then use the new prompt to try a corrected command.
Common mistake Expecting a script to continue after a ValueError
What it looks likeA conversion fails, but the learner expects the next calculation and print statement to run.
Why it failsAn unhandled exception causes the script to stop immediately, so later statements are not executed.
Do this insteadUse the traceback to find the failing statement and recognize that error handling with try and except is needed for graceful responses.
Common mistake Calling every conversion problem a type problem
What it looks likeThe input is the string fred and the program calls float() on it.
Why it failsThe argument is a string, but its contents are not a valid floating-point value. This situation produces
ValueError.Do this insteadAsk whether the argument has an appropriate type and whether its value is valid for the requested conversion.
Common mistake Looking only at the final line of a traceback
What it looks likeThe learner notices ValueError but ignores the file, line number, and statement.
Why it failsThe earlier traceback lines locate where the failure occurred and show the call sequence that led to it.
Do this insteadRead 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?
- 1Same exception
In both settings, the invalid value causes
ValueError. - 2Interactive response
The interpreter reports the error and returns a prompt, allowing another command.
- 3Script 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.
ValueErroroccurs when a function receives an argument of the correct type but an inappropriate value, such as a non-numeric string passed toint()orfloat().- 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.