Concepts / Catching Exceptions with try and except Blocks

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.

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

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.

Error occursInteractiveinterpreterError messageNew promptPython scriptTracebackScript terminationcommand entered directlyreportsreturnsscript is runningprintsleads to
What happens next after an error occurs in the interactive interpreter compared with a script?

The ValueError Case

Definition

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.

String valueletters or non-numericcharactersint() or float()conversion operationValueErrorinvalid valueis passed tocannot interpret value
What happens when Python tries to convert an invalid string to a numeric type?

Following the Fahrenheit Example

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

  1. 1
    Read the input

    The script receives the string fred as its input.

  2. 2
    Attempt conversion

    The statement fahr = float(inp) asks float() to convert that string to a floating-point number.

  3. 3
    Raise the exception

    Because fred is not a valid value for float(), Python raises a ValueError.

  4. 4
    Stop the script

    The Celsius calculation and the print statement do not execute because the script terminates at the conversion failure.

Result

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

Definition

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.

Input fredfloat(inp)fahren.py line 2ValueError tracebackinvalid float conversionRemaining statementsnot executedScript terminationpassed toraisesskipsscript stops
How does a traceback show where an unhandled error occurred, and what happens to the remaining statements?

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.

try blockoperation may failConversion operationExceptionfailure is detectedexcept blockprogram responseGraceful responserunsmay raisehandled byresponds instead of crashing
How does control flow change when code inside a try block raises an exception, and where does execution continue?

Mistakes to Avoid

  • Common mistake

    Treating every conversion failure as a type problem

    What it looks like

    A string is passed to float(), but the string contains fred.

    Why it fails

    The argument is a string, but its value is not a valid floating-point representation. This is a ValueError.

    Do this instead

    Check 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 like

    A script fails while converting input and the learner expects its later statements to run.

    Why it fails

    An unhandled exception stops the script immediately.

    Do this instead

    Use the traceback to identify the failure and recognize that later statements were not executed.

  • Common mistake

    Ignoring the traceback details

    What it looks like

    Looking only at the word ValueError and not at the file, line, or statement.

    Why it fails

    The traceback provides the location and call sequence needed to find the source of the error.

    Do this instead

    Read 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 like

    A learner recovers from invalid input at the interpreter prompt and expects the saved program to recover automatically.

    Why it fails

    The interpreter returns a new prompt, but a script terminates when the exception is unhandled.

    Do this instead

    Plan explicit error handling for operations that may receive invalid data.

Check Your Understanding

MEDIUM

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

  1. 1
    The interactive interpreter reports an error and returns a new prompt, allowing you to continue with another command.
  2. 2
    An unhandled exception in a script stops the script immediately and prevents later statements from executing.
  3. 3
    A ValueError occurs when a function receives a suitable broad type but an inappropriate value, such as a non-numeric string passed to int() or float().
  4. 4
    A traceback identifies the error type, the file and line involved, the relevant statement, and the sequence of calls leading to the failure.
  5. 5
    try 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.
  • ValueError describes 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.

Related concepts

More concepts starting with C