1 / 21

Exception-Handling Overview

Exception-Handling Overview. Exception: when something unforeseen happens and causes an error Exception handler catches a raised/thrown exception try statement encloses code that may cause exception use raise statement to indicate that an exception occurred Exception handling

wyanet
Télécharger la présentation

Exception-Handling Overview

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

  3. Using if’s • Ugly alternative: what is the main program and what is error handling?? isdigit doesn’t even suffice if the user inputs a float

  4. if’s vs. exception handling • Exception handling is mostly for when you think you won’t get some bad value. • if’s are for when you know that some values will be bad, i.e. you expect them.

  5. 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 fatal, 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.

  6. 0 1 2 3 4 5 6 7 8 9 ... n-1 ... end-of-file marker 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 Fig. 14.2 Python’s view of a file of n bytes.

  7. 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()

  8. CD management cd.py

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

  10. Save cd collection to a file, line by line cd.py Alternatives: file.write(..) : no newline print >> file, .. : newline sys.exit method terminates the program and prints message

  11. File cdsave.dat Test Prince Purple Rain 7.4 Oscar Peterson Night Train 8.0 Beatles Sgt. Pepper 9.6 cdtest.py Program output Prince / Purple Rain (rating: 7.4) Oscar Peterson / Night Train (rating: 8.0) Beatles / Sgt. Pepper (rating: 9.6)

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

  13. 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)

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

  15. 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!!] cd2test.py

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

  17. New load method..? Prince Purple Rain 7.4 Groundbreaking! Oscar Peterson Night Train 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!! • Which attributes are which in the saved file?? • No longer 3 lines per cd  • Change save method or • Write super-intelligent • load method

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

  19. Testing the pickle save method .. S'Purple Rain' p6 sS'comments' p7 (lp8 S'Groundbreaking!' p9 asS'artist' p10 S'Prince' p11 sba(icd_pickle CD .. cd_pickletest.py Excerpt from file cd_picklesave.dat

  20. Testing the load method We need a CDcollection object for which we can call the load method to retrieve the pickled object cd_pickletest_load.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!!] Beatles / A Hard Day's Night (rating: 6.8) [First album with all Lennon/McCartney songs]

  21. ..on to the exercises

More Related