ExceptionHandling Overview Exception when something unforeseen happens and

  • Slides: 19
Download presentation
Exception-Handling Overview • Exception: when something unforeseen happens and causes an error • Exception

Exception-Handling Overview • Exception: when something unforeseen happens and causes an error • Exception handling – improves program clarity by removing error-handling code from the “main line” of the program – Improves a program’s fault tolerance • Exception handler catches a raised/thrown exception • try statement encloses code that may cause exception • use raise statement to indicate an exception occurred 1

number 1 = raw_input( "Enter numerator: " ) number 2 = raw_input( "Enter denominator:

number 1 = raw_input( "Enter numerator: " ) number 2 = raw_input( "Enter denominator: " ) # attempt to convert and divide values try: number 1 = float( number 1 ) number 2 = float( number 2 ) User might raise a Value. Error by entering a string that cannot be converted to float result = number 1 / number 2 # float raises a Value. Error exception except Value. Error: Division by zero raises Zero. Division. Error exception print "You must enter two numbers" # division by zero raises a Zero. Division. Error exception except Zero. Division. Error: print "Attempted to divide by zero" # else clause's suite executes if try suite raises no exceptions else: print "%. 3 f / %. 3 f = %. 3 f" % ( number 1, number 2, result )

How and where to handle exceptions Import codon translation module, look up codon not

How and where to handle exceptions Import codon translation module, look up codon not in the dictionary. What to do with the exception? • Should the module handle the exception? – return ‘? ’ ? – print error message? – exit? • . . or should the importing main program? – if translating long sequence, result will be meaningless – if outputting to file, print statements will corrupt it If user should know he’s doing something stupid, don’t catch exception (or raise one!), forcing him to realize his mistake If a meaningful or default response can be given which would not surprise the user, do that. 3

14. 3 Files and Streams • Python views files as sequential streams of bytes

14. 3 Files and Streams • Python views files as sequential streams of bytes • Each file ends with an end-of-file marker • Opening a file creates an object associated with a stream 0 1 2 3 4 5 6 7 8 9 . . . Fig. 14. 2 n-1 end-of-file marker Python’s view of a file of n bytes. 4

Files and Streams • Three file streams created when Python program executes – sys.

Files and Streams • Three file streams created when Python program executes – sys. stdin (standard input stream) – sys. stdout (standard output stream) – sys. stderr (standard error stream) • Defaulted to keyboard, screen and screen, respectively (raw_input uses stdin, print uses stdout) • Redirect: print >> file, “Yes sir we have no bananas” • Force print now: sys. stdout. flush() 5

cd. py CD management 7

cd. py CD management 7

cd. py Implicitly calling the __str__ method of the cd class 8

cd. py Implicitly calling the __str__ method of the cd class 8

cd. py Save cd collection to a file, line by line sys. exit method

cd. py Save cd collection to a file, line by line sys. exit method terminates the program and prints message 9

Test Prince Purple Rain 7. 4 Oscar Peterson File cdsave. dat Night Train 8.

Test Prince Purple Rain 7. 4 Oscar Peterson File cdsave. dat Night Train 8. 0 Beatles cdtest. py Program output Sgt. Pepper 9. 6 Prince / Purple Rain (rating: 7. 4) Oscar Peterson / Night Train (rating: 8. 0) Beatles / Sgt. Pepper (rating: 9. 6) 10

Load cd collection from file, line by line cd. py Remove the trailing newline

Load cd collection from file, line by line cd. py Remove the trailing newline Create new CD object and add to collection 11

Testing the load method >>> from cd import CD, CDcollection >>> cds = CDcollection()

Testing the load method >>> from cd import CD, CDcollection >>> cds = CDcollection() >>> cds. load( 'cdsave. dat') >>> print cds Prince / Purple Rain (rating: 7. 4) Oscar Peterson / Night Train (rating: 8. 0) Beatles / Sgt. Pepper (rating: 9. 6) 12

cd 2. py Extending cd class with comments Write each comment on a line

cd 2. py Extending cd class with comments Write each comment on a line of its own, with a suitable number of spaces 13

cd 2 test. py Prince / Purple Rain (rating: 7. 4) [Groundbreaking!] Oscar Peterson

cd 2 test. py Prince / Purple Rain (rating: 7. 4) [Groundbreaking!] Oscar Peterson / Night Train (rating: 8. 0) [Got it in a Starbucks in West L. A. ] [Good album, especially the Gershwin songs. ] Beatles / Sgt. Pepper (rating: 9. 6) [Groundbreaking AND evergreen!!] 14

cd 2. py New save method Write each comment on a line of its

cd 2. py New save method Write each comment on a line of its own after artist, title and rating 15

New load method. . ? Which attributes are which in the saved file? ?

New load method. . ? Which attributes are which in the saved file? ? Prince Purple Rain 7. 4 Groundbreaking! No longer 3 lines per cd Oscar Peterson • Change save method or Night Train • Write super-intelligent load method 8. 0 Got it in a Starbucks in West L. A. Good album, especially the Gershwin songs. Beatles Sgt. Pepper 9. 6 Groundbreaking AND evergreen!! 16

New load/save methods using module c. Pickle cd_pickle. py Write entire object (list of

New load/save methods using module c. Pickle cd_pickle. py Write entire object (list of CD objects) to file Easy to load object back into memory if you’re completely sure what kind of object the file 17 contains

cd_pickletest. py Testing the pickle save method Excerpt from file cd_picklesave. dat . .

cd_pickletest. py Testing the pickle save method Excerpt from file cd_picklesave. dat . . S'Purple Rain' p 6 s. S'comments' p 7 (lp 8 S'Groundbreaking!' p 9 as. S'artist' p 10 S'Prince' p 11 sba(icd_pickle CD. . 18

cd_pickletest_load. py Testing the load method We need a CDcollection object for which we

cd_pickletest_load. py Testing the load method We need a CDcollection object for which we can call the load method to retrieve the pickled object Prince / Purple Rain (rating: 7. 4) [Groundbreaking!] Oscar Peterson / Night Train (rating: 8. 0) [Got it in a Starbucks in West L. A. ] [Good album, especially the Gershwin songs. ] Beatles / Sgt. Pepper (rating: 9. 6) [Groundbreaking AND evergreen!!] Beatles / A Hard Day's Night (rating: 6. 8) [First album with all Lennon/Mc. Cartney songs] 19

. . on to the exercises 20

. . on to the exercises 20