Concepts / Catching Exceptions with try and except Blocks

Catching Exceptions with try and except Blocks

The Python interpreter recovers from errors and returns a prompt; a script terminates immediately with a traceback.

  • Programming

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.

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

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.

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

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?

Read the input: The script receives the string fred as its input.

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

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

Stop 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.

passed toraisesskipsscript stopsInput fredfloat(inp)fahren.py line 2ValueError tracebackinvalid float conversionRemaining statementsnot executedScript termination
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.

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

Mistakes to Avoid

  • Treating every conversion failure as a type problem

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

    Fix: Check whether the value is appropriate for the requested conversion, not only whether the broad argument type is acceptable.

  • Assuming that a script will return to a prompt after an error

    An unhandled exception stops the script immediately.

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

  • Ignoring the traceback details

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

    Fix: Read the file and line information, the displayed statement, and the final error message together.

  • Assuming that successful interactive experimentation proves a script is safe

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

    Fix: 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. The interactive interpreter reports an error and returns a new prompt, allowing you to continue with another command.
  2. An unhandled exception in a script stops the script immediately and prevents later statements from executing.
  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. A traceback identifies the error type, the file and line involved, the relevant statement, and the sequence of calls leading to the failure.
  5. try and except blocks provide the foundation for responding gracefully when operations such as input conversion fail.

Key Takeaways

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