Catching Exceptions with try and except Blocks
An unhandled exception makes a script terminate, so a program cannot assume that every input or operation will succeed.
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
An error does not feel the same everywhere in Python. When you type a command directly into the interactive interpreter, Python reports the error and then gives you a new prompt. You can try another command. When the same kind of error occurs while running a script from a file, the script stops immediately and Python prints a traceback. This difference explains why an experiment can seem easy to recover from in the interpreter while a saved program can terminate unexpectedly.
The ValueError Case
A ValueError occurs when a function receives an argument of the correct type but an inappropriate value. During numeric conversion, this happens when int() or float() receives a string containing letters or other characters that do not represent a valid number.
The important distinction is between type and value. A string is an appropriate type of argument for conversion functions such as int() and float(). However, a particular string may still contain a value that cannot be interpreted as a number. The source example int('hello') produces a ValueError for this reason.
Following the Fahrenheit Example
A temperature conversion that receives invalid input
A script reads a Fahrenheit temperature, converts it to Celsius, and prints the result. What happens if the supplied input is fred?
- 1Read the input
The script receives the string fred as its input.
- 2Attempt conversion
The statement fahr =
float(inp)asksfloat()to convert that string to a floating-point number. - 3Raise the exception
Because fred is not a valid value for
float(), Python raises aValueError. - 4Stop the script
The Celsius calculation and the print statement do not execute because the script terminates at the conversion failure.
The script ends with a ValueError before it can calculate or print the converted temperature.
With valid input, the Fahrenheit-to-Celsius script works normally. With invalid input, the failure occurs during conversion rather than during the later calculation. This location matters: the statements after the failed conversion are never reached.
Reading a Traceback
A traceback is a detailed report showing where an exception occurred and the sequence of calls that led to it. It helps you locate the source of the error.
In the Fahrenheit example, the traceback begins with the phrase Traceback (most recent call last). It identifies fahren.py, points to line 2, and identifies the top-level script context as in <module>. It then shows the statement fahr = float(inp), followed by the specific message ValueError: could not convert string to float: 'fred'. Reading these parts from general context toward the final error message lets you connect the failure to the exact conversion operation.
Why try and except Matter
An unhandled exception makes a script terminate, so a program cannot assume that every input or operation will succeed. Users may enter invalid data, networks may fail, and files may not exist. try and except blocks are the next step in responding to these exceptions: they allow a program to handle an error instead of simply crashing.
Mistakes to Avoid
Common mistake Treating every conversion failure as a type problem
What it looks likeA string is passed to float(), but the string contains fred.
Why it failsThe argument is a string, but its value is not a valid floating-point representation. This is a
ValueError.Do this insteadCheck whether the value is appropriate for the requested conversion, not only whether the broad argument type is acceptable.
Common mistake Assuming that a script will return to a prompt after an error
What it looks likeA script fails while converting input and the learner expects its later statements to run.
Why it failsAn unhandled exception stops the script immediately.
Do this insteadUse the traceback to identify the failure and recognize that later statements were not executed.
Common mistake Ignoring the traceback details
What it looks likeLooking only at the word ValueError and not at the file, line, or statement.
Why it failsThe traceback provides the location and call sequence needed to find the source of the error.
Do this insteadRead the file and line information, the displayed statement, and the final error message together.
Common mistake Assuming that successful interactive experimentation proves a script is safe
What it looks likeA learner recovers from invalid input at the interpreter prompt and expects the saved program to recover automatically.
Why it failsThe interpreter returns a new prompt, but a script terminates when the exception is unhandled.
Do this insteadPlan explicit error handling for operations that may receive invalid data.
Check Your Understanding
Explain what happens in each situation: an invalid numeric conversion entered directly into the interactive interpreter; the same conversion inside a script; and the same conversion protected by an error-handling response. In your explanation, identify the ValueError, describe what the traceback contributes, and state whether the remaining script statements execute.
Hints
- Separate interactive interpreter behavior from script behavior.
- Ask whether the string represents a valid number.
- For the script case, identify what happens immediately after the exception.
- For the handled case, connect try and except with responding gracefully instead of crashing.
Key Takeaways
- 1The interactive interpreter reports an error and returns a new prompt, allowing you to continue with another command.
- 2An unhandled exception in a script stops the script immediately and prevents later statements from executing.
- 3A
ValueErroroccurs when a function receives a suitable broad type but an inappropriate value, such as a non-numeric string passed toint()orfloat(). - 4A traceback identifies the error type, the file and line involved, the relevant statement, and the sequence of calls leading to the failure.
- 5try and except blocks provide the foundation for responding gracefully when operations such as input conversion fail.
At a glance
- Interactive Python recovers by displaying an error and returning a prompt; a script terminates on an unhandled exception.
ValueErrordescribes an invalid value, including a string that cannot be converted to a number.- A traceback is a roadmap from the failing operation to the exact line and call sequence that caused the exception.
- try and except blocks are used to give programs a deliberate response when an operation fails.