Difference between revisions of "CSC111 Lab 9 2015"
(→preparation) |
(→preparation) |
||
Line 64: | Line 64: | ||
return x | return x | ||
+ | </source> | ||
+ | <br /> | ||
+ | * Run your program and try different invalid inputs, such as strings or floats. You can also try just pressing the '''Return''' key, indicating that you are not providing anything to the input function. Verify that your program catches all these invalid entries and does not crash. | ||
+ | <br /> | ||
+ | ==Exercise== | ||
+ | <br /> | ||
+ | =Code in need of try/except statements= | ||
+ | <br /> | ||
+ | |||
+ | * 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: | ||
+ | <tt><font color="red"> | ||
+ | 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 | ||
+ | </font></tt> | ||
+ | |||
+ | :what you are interested in is '''IndexError'''. This is the ''exception'' you want to guard your code against. | ||
+ | |||
+ | <code><pre> | ||
+ | |||
+ | try: | ||
+ | ........ | ||
+ | ........ | ||
+ | except IndexError: | ||
+ | ......... | ||
+ | |||
+ | </pre></code> | ||
+ | * Verify that you have made your functions more robust to erroneous input/data. | ||
+ | <br /> | ||
+ | |||
+ | ==Code== | ||
+ | <br /> | ||
+ | |||
+ | <br /> | ||
+ | <source lang="python"> | ||
+ | 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() | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | |||
+ | |||
+ | |||
+ | ==Solution== | ||
+ | <br /> | ||
+ | <source lang="python"> | ||
+ | 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() | ||
</source> | </source> | ||
<!-- /showafterdate --> | <!-- /showafterdate --> |
Revision as of 07:36, 29 March 2015
--D. Thiebaut (talk) 07:14, 29 March 2015 (EDT)
Contents
Exceptions
preparation
- Create a new program called lab9_1.py, and copy this code to the new Idle window.
# lab9_1.py # Your name here # getInput: returns an integer larger # than 0. Expected to be robust def getInput(): while True: x = int( input( "Enter an integer greater than 0: " ) ) if x <= 0: print( "Invalid entry. Try again!" ) else: return x def main(): num = getInput() print( "You have entered", num ) main()
- Test it with numbers such as -3, -10, 0, 5. Verify that the input function works well when you enter numbers.
- Test your program again, and this time enter expressions such as "6.3", or "hello" (without the quotes).
- Make a note of the Error reported by Python:
- Modify your function and add code that will catch the exception:
# getInput: returns an integer larger # than 0. Catches Value errors def getInput(): # repeat forever... while True: # try to get an int try: x = int( input( "Enter an integer greater than 0: " ) ) except ValueError: # the user must have entered something other than an int print( "Invalid entry. Not an integer. Try again!" ) continue # No errors caught. See if the number is negative if x <= 0: print( "You entered a negative number. Try again!" ) else: # finally, we can return x as it is an int that is >0 return x
- Run your program and try different invalid inputs, such as strings or floats. You can also try just pressing the Return key, indicating that you are not providing anything to the input function. Verify that your program catches all these invalid entries and does not crash.
Exercise
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()