Chapter 13 – Exceptions

Sections 13.1 - 13.3

\(\boxdot\) Exceptions
  • An exception in Python is an event or state that cannot be controlled by the normal flow of the program.

  • Divide by zero. This event can be controlled with proper selection or case handling.

    if den != 0.0:  
        quo = num / den   
    else:
        print("Denominator is equal to zero!")  
  • In Python, all errors are handled as exceptions, but not all exceptions are errors.

  • Syntax:

    try:  
        (code block)  
    except ExceptionName1:  
        (code block for this type of exception)  
    except ExceptionName2:
        (code block for this type of exception)  
    else:   (optional)  
    finally: (optional)  
\(\boxdot\) File Handling Exceptions
  • Initial Program:

    def process_cc_data(f_n, an):
        f_i = open(f_n, 'r')
        f_o = open('A' + an + '.txt', 'w')
        for line in f_i:
            l_strip = line.strip()
            items = l_strip.split()
            if items[0] == an:
                mn = items[1][:2]
                dy = items[1][2:4]
                yr = items[1][4:]
                amt = items[4]
                rt = items[3]
                f_o.write("On {0:2s}/{1:2s}/{2:4s} your account had a charge of ${3:>6.2f} at {4:<30s}\n".format(mn, dy, yr, float(amt), rt))
        f_o.close()
    
    
    def main():
        f_name = 'cc_trans_u.txt'     # assuming an updated file  exists
        process_cc_data(f_name, '10056')
    
    
    main()
  • The data set named cc_trans.txt:

    10056    01012017    c    Amazon                  33.85 
    10056    01022017    c    Oneota_Market           12.48 
    10056    01052017    c    Amazon                  47.56 
    10056    01062017    c    T_Bocks                  4.27 
    10056    01082017    c    Walmart                167.14 
    10056    01092017    c    Fairway                 82.92 
    10056    01142017    c    Walmart                 92.70 
    10056    01182017    c    Walmart                 88.15 
    10056    01212017    c    Amazon                  32.73 
    10056    01222017    c    Walmart                164.14 
    10056    01252017    c    Roscoes                 13.35 
    10056    01292017    c    Viking_Theatre          26.29 
    10289    01012017    c    Amazon                  51.49 
    10289    01022017    c    Pulpit_Rock             31.32 
    10289    01042017    c    Roscoes                  6.60 
    10289    01042017    c    Toppling_Goliath         7.21 
    10289    01062017    c    Fairway                 55.52 
    10289    01062017    c    Amazon                  26.47 
    10289    01072017    c    Walmart                 27.23 
    10289    01132017    c    Oneota_Market            7.93 
    10289    01182017    c    Toppling_Goliath        50.54 
    10289    01192017    c    Koreanna                23.65 
    10289    01242017    c    T_Bocks                 28.43 
    19542    01022017    c    Fairway                 44.87   
  • File Exception Fix:

    def process_cc_data(f_n, an):
        f_i = open(f_n, 'r')
        f_o = open('A' + an + '.txt', 'w')
        for line in f_i:
            l_strip = line.strip()
            items = l_strip.split()
            if items[0] == an:
            mn = items[1][:2]
            dy = items[1][2:4]
            yr = items[1][4:]
            amt = items[4]
            rt = items[3]
            f_o.write("On {0:2s}/{1:2s}/{2:4s} your account had a charge of ${3: >6.2f} at {4:<30s}\n".format(mn, dy, yr, float(amt), rt))
       f_o.close()
    
    
    def main():
        try:
            f_name = 'cc_trans_u.txt'
            process_cc_data(f_name, '10056')
        except FileNotFoundError:
            print('Updated file not found')
            f_name = 'cc_trans.txt'
            process_cc_data(f_name, '10056')
        except PermissionError:
            print('File access not permited')
    
    
    main()