Difference between revisions of "CSC111 Exercises with Exceptions: try/except"

From dftwiki3
Jump to: navigation, search
(Solution)
 
(8 intermediate revisions by the same user not shown)
Line 7: Line 7:
 
<br />
 
<br />
 
<bluebox>
 
<bluebox>
The exercises below deal with protecting Python code that might crash with '''try/catch''' statements to make the program robust.
+
The exercises below deal with protecting Python code that might crash with '''try/except''' statements to make the program robust.
 
</bluebox>
 
</bluebox>
 
<br />
 
<br />
Line 51: Line 51:
 
<source lang="python">
 
<source lang="python">
 
def example1():
 
def example1():
     x = eval( input( "enter a number: " ) )
+
     for i in range( 3 ):
    y = eval( input( "enter another number: " ) )
+
        x = int( input( "enter a number: " ) )
    print( x, '/', y, '=', x/y )
+
        y = int( input( "enter another number: " ) )
 +
        print( x, '/', y, '=', x/y )
  
 
def example2( L ):
 
def example2( L ):
 
     print( "\n\nExample 2" )
 
     print( "\n\nExample 2" )
 
     sum = 0
 
     sum = 0
 +
    sumOfPairs = []
 
     for i in range( len( L ) ):
 
     for i in range( len( L ) ):
         sum = sum + L[i]
+
         sumOfPairs.append( L[i]+L[i+1] )
  
     print( "sum = ", sum )
+
     print( "sumOfPairs = ", sumOfPairs )
  
def example3( L ):
 
    print( "\n\nExample 3" )
 
    sum = 0
 
    for i in range( 6 ):
 
        sum = sum + L[i]
 
  
    print( "sum = ", sum )
+
def printUpperFile( fileName ):
 +
  file = open( fileName, "r" )
 +
  for line in file:
 +
      print( line.upper() )
 +
  file.close()
 
      
 
      
 
def main():
 
def main():
Line 77: Line 78:
 
     example2( [ 10, 3, 5, 6, "NA", 3 ] )
 
     example2( [ 10, 3, 5, 6, "NA", 3 ] )
 
     example3( [ 10, 3, 5, 6 ] )
 
     example3( [ 10, 3, 5, 6 ] )
      
+
 
 +
     printUpperFile( "doesNotExistYest.txt" )
 +
    printUpperFile( "./Dessssktop/misspelled.txt" )
 +
 
 
main()
 
main()
  
 
</source>
 
</source>
 
<br />
 
<br />
==File Examples==
 
<br />
 
===Example 1===
 
What could possibly go wrong with this code?
 
<source lang="python">
 
def printUpperFile( fileName ):
 
  file = open( fileName, "r" )
 
  for line in file:
 
      print( line.upper() )
 
  file.close()
 
  
printUpperFile( "doesNotExistYest.txt" )
 
printUpperFile( "./Dessssktop/misspelled.txt" )
 
</source>
 
  
<onlydft>
+
 
==Solution==
 
==Solution==
 
<br />
 
<br />
 
<source lang="python">
 
<source lang="python">
 
def example1():
 
def example1():
     x = eval( input( "enter a number: " ) )
+
     while True:
    y = eval( input( "enter another number: " ) )
+
      try:
    try:
+
            x = int( input( "enter a number: " ) )
        print( x, '/', y, '=', x/y )
+
            y = int( input( "enter another number: " ) )
    except ZeroDivisionError:
+
            print( x, '/', y, '=', x/y )
        print( "Cannot divide by 0" )
+
            break
 
+
      except ZeroDivisionError:
 +
            print( "Can't divide by 0!" )
 +
      except ValueError:
 +
            print( "That doesn't look like a number!" )
 +
      except:
 +
            print( "something unexpected happend!" )
 +
           
 +
           
 
def example2( L ):
 
def example2( L ):
 
     print( "\n\nExample 2" )
 
     print( "\n\nExample 2" )
 +
    print( "L          = ", L )
 
     sum = 0
 
     sum = 0
 +
    sumOfPairs = []
 
     for i in range( len( L ) ):
 
     for i in range( len( L ) ):
        try:
+
            try:
            sum = sum + L[i]
+
                sumOfPairs.append( L[i]+L[i+1] )
        except TypeError:
+
            except IndexError:
            pass
+
                continue
           
+
            except TypeError:
     print( "sum = ", sum )
+
                continue
 +
   
 +
     print( "sumOfPairs = ", sumOfPairs )
  
def example3( L ):
+
def printUpperFile( fileName ):
     print( "\n\nExample 3" )
+
     try:
     sum = 0
+
      file = open( fileName, "r" )
    for i in range( 6 ):
+
     except FileNotFoundError:
        try:
+
      print( "***Error*** File", fileName, "not found!" )
            sum = sum + L[i]
+
      return False
        except IndexError:
+
   
            break
+
    for line in file:
         except TypeError:
+
         print( line.upper() )
            pass
+
     file.close()
     print( "sum = ", sum )
+
    return True
 
      
 
      
 
def main():
 
def main():
     #example1()
+
     example1()
 +
   
 
     L = [ 10, 3, 5, 6, 9, 3 ]
 
     L = [ 10, 3, 5, 6, 9, 3 ]
     #example2( L )
+
     example2( L )
     #example2( [ 10, 3, 5, 6, "NA", 3 ] )
+
 
    example3( [ 10, 3, 5, 6 ] )
+
     L = [ 10, 3, "NA", 6, 9, 3 ]
     example3( [ "NA", 10, 3, 5, 6 ] )
+
     example2( L )
 
      
 
      
 +
    open( "doesNotExistYest.txt", "w" ).close()
 +
 +
    printUpperFile( "doesNotExistYest.txt" ):
 +
       
 +
    printUpperFile( "./Dessssktop/misspelled.txt" )
 +
 +
 
main()
 
main()
 +
</source>
  
</source>
 
</onlydft>
 
 
<br />
 
<br />
 
<br />
 
<br />

Latest revision as of 12:51, 4 April 2014

--D. Thiebaut (talk) 09:05, 2 April 2014 (EDT)






The exercises below deal with protecting Python code that might crash with try/except statements to make the program robust.





Code in need of try/except statements


  • The program below is not very robust. We can easily make it crash.
  • Observe each function and see how to make it fail, or see why it will fail the way it is called
  • Make the program crash. Register the XXXXError that is generated. For example, if the output of the crash looks like this:

Traceback (most recent call last):
 File "/Users/thiebaut/Desktop/except0.py", line 29, in <module>
   main()
 File "/Users/thiebaut/Desktop/except0.py", line 27, in main
   example3( [ 10, 3, 5, 6 ] )
 File "/Users/thiebaut/Desktop/except0.py", line 18, in example3
   sum = sum + L[i]
IndexError: list index out of range

what you are interested in is IndexError. This is the exception you want to guard your code against.

  try:
      ........
      ........
  except IndexError:
      .........

  • Verify that you have made your functions more robust to erroneous input/data.


Code



def example1():
    for i in range( 3 ):
        x = int( input( "enter a number: " ) )
        y = int( input( "enter another number: " ) )
        print( x, '/', y, '=', x/y )

def example2( L ):
    print( "\n\nExample 2" )
    sum = 0
    sumOfPairs = []
    for i in range( len( L ) ):
        sumOfPairs.append( L[i]+L[i+1] )

    print( "sumOfPairs = ", sumOfPairs )


def printUpperFile( fileName ):
   file = open( fileName, "r" )
   for line in file:
       print( line.upper() )
   file.close()
    
def main():
    example1()
    L = [ 10, 3, 5, 6, 9, 3 ]
    example2( L )
    example2( [ 10, 3, 5, 6, "NA", 3 ] )
    example3( [ 10, 3, 5, 6 ] )

    printUpperFile( "doesNotExistYest.txt" )
    printUpperFile( "./Dessssktop/misspelled.txt" )

main()



Solution


def example1():
    while True:
       try:
            x = int( input( "enter a number: " ) )
            y = int( input( "enter another number: " ) )
            print( x, '/', y, '=', x/y )
            break
       except ZeroDivisionError:
            print( "Can't divide by 0!" )
       except ValueError:
            print( "That doesn't look like a number!" )
       except:
            print( "something unexpected happend!" )
            
            
def example2( L ):
    print( "\n\nExample 2" )
    print( "L          = ", L )
    sum = 0
    sumOfPairs = []
    for i in range( len( L ) ):
            try:
                sumOfPairs.append( L[i]+L[i+1] )
            except IndexError:
                continue
            except TypeError:
                continue
    
    print( "sumOfPairs = ", sumOfPairs )

def printUpperFile( fileName ):
    try:
       file = open( fileName, "r" )
    except FileNotFoundError:
       print( "***Error*** File", fileName, "not found!" )
       return False
    
    for line in file:
        print( line.upper() )
    file.close()
    return True
    
def main():
    example1()
    
    L = [ 10, 3, 5, 6, 9, 3 ]
    example2( L )

    L = [ 10, 3, "NA", 6, 9, 3 ]
    example2( L )
    
    open( "doesNotExistYest.txt", "w" ).close()

    printUpperFile( "doesNotExistYest.txt" ):
        
    printUpperFile( "./Dessssktop/misspelled.txt" )


main()