Skip to main content
Engineering LibreTexts

14.4: Handling Exceptions

  • Page ID
    117616
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    Learning Objectives

    By the end of this section you should be able to

    • Describe two exceptions that may occur when reading files.
    • Write try/except statements that handle built-in exceptions.

    Runtime errors

    Various errors may occur when reading a file:

    • FileNotFoundError: The filename or path is invalid.
    • IndexError/ValueError: The file's format is invalid.
    • Other errors caused by invalid contents of a file.

    When an error occurs, the program terminates with an error message.

    Example 14.4

    Typo in a file

    A file named food_order.txt has the following contents:

        5 sandwiches
        4 chips
        1 pickle
        soft drinks

    The following program expects each line of the file to begin with an integer:

        for line in open("food_order.txt"):
            space = line.index(" ")
            qty = int(line[:space])
            item = line[space+1:-1]
            print(qty, item)

    Unfortunately, the line "soft drinks" does not begin with an integer. As a result, the program terminates and displays an error message:

        Traceback (most recent call last):
          File "food_order.py", line 3
            qty = int(line[:space])
        ValueError: invalid literal for int() with base 10: 'soft'
    Concepts in Practice: Common exceptions

    What error might occur in each situation?

    1.
    The line "soft drinks" is changed to "3-4 soft drinks".
    1. FileNotFoundError
  • IndexError
  • ValueError
  • 2.
    for line in open("food_order.text"):
    1. FileNotFoundError
    2. IndexError
    3. ValueError
    3.
    parts = line.split()
    qty = parts[0]
    item = parts[1]
    
    1. FileNotFoundError
    2. IndexError
    3. ValueError
    Exploring further

    The Built-in Exceptions page of the Python Standard Library explains the meaning of each exception.

    Try and except

    Programs can be designed to handle exceptions, rather than terminate. A try statement runs code that might raise an exception. An except clause runs code in response to the exception.

    Example 14.5

    Try to open a file

    The following program, named try_open.py, asks the user for a filename and counts the number of lines in the file.

        name = input("Enter a filename: ")
        try:
            file = open(name)
            lines = file.readlines()
            count = len(lines)
            print(name, "has", count, "lines")
        except FileNotFoundError:
            print("File not found:", name)
        print("Have a nice day!")

    When running this program with the input try_open.py, the name of the program file, the output is:

        Enter a filename: try_open.py
        try_open.py has 9 lines
        Have a nice day!

    If the filename does not exist, a FileNotFoundError is raised on line 3. The program then jumps to the except clause on line 7 and continues to run. The resulting output is:

        Enter a filename: try_open.txt
        File not found: try_open.txt
        Have a nice day!
    Concepts in Practice: Predicting output with exceptions

    For each code snippet, what is the output?

    4.
    word = "one"
    try:
      number = int(word)
      print(word, "equals", number)
    except ValueError:
      print(word, "is not a number")
    
    1. one equals 1
  • one is not a number
  • ValueError: invalid literal for int() with base 10: 'one'
  • 5.
    word = "one"
    try:
      number = int(word)
      print(word, "equals", number)
    except IndexError:
      print(word, "is not a number")
    
    1. one equals 1
    2. one is not a number
    3. ValueError: invalid literal for int() with base 10: 'one'
    6.
    word = "one"
    try:
      char = word[3]
      print("The char is", char)
    except:
      print("That didn't work")
    
    1. The char is e
    2. That didn't work
    3. IndexError: string index out of range
    Try It: Type analyzer

    Analysis programs often need to find numbers in large bodies of text. How can a program tell if a string like "123.45" represents a number? One approach is to use exceptions:

    1. Try converting the string to an integer. If no ValueError is raised, then the string represents an integer.
    2. Otherwise, try converting the string to a float. If no ValueError is raised, then the string represents a float.
    3. Otherwise, the string does not represent a number.

    Implement the get_type() function using this approach. The provided main block calls get_type() for each word in a file. get_type() should return either "int", "float", or "str", based on the word. The output for the provided data.txt is:

        str: Hello
        int: 100
        str: times!
        float: 3.14159
        str: is
        str: pi.
    Try It: United countries

    Write a program that prompts the user to input a word and a filename. The program should print each line of the file that contains the word. Here is an example run of the program (user input in bold):

        Enter a word: United
        Enter a filename: countries.csv
        United Arab Emirates,9890402,83600,118
        United Kingdom,67886011,241930,281
        United States of America,331002651,9147420,36

    This example uses a file named countries.csv based on the alphabetical list of countries from Worldometer. Each line of the file includes a country's name, population, land area, and population density, separated by commas.

    The user might incorrectly type the filename (Ex: countries.txt instead of countries.csv). Your program should output an error message if the file is not found, and keep prompting the user to input a filename until the file is found:

        ...
        Enter a filename: countries
        File not found: countries
        Enter a filename: countries.txt
        File not found: countries.txt
        Enter a filename: countries.csv
        ...

    Hint: Try to open the file specified by the user. A FileNotFoundError is raised if the filename is invalid.


    This page titled 14.4: Handling Exceptions is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.