Download - Lecture 12 exceptions
![Page 1: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/1.jpg)
Introduction to computational thinking
Module 12 : Exceptions
Module 12 : Exceptions
Asst Prof Michael LeesOffice: N4‐02c‐76
email: mhlees[at]ntu.edu.sg1
![Page 2: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/2.jpg)
Contents
1. Why & What are exceptions2. Try/Except group3. Exception Philosophy4. else and finally suites
Module 12 : Exceptions
Chapter 14
2
![Page 3: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/3.jpg)
Dealing with problems
• Most modern languages provide ways to deal with ‘exceptional’ situations
• Try to capture certain situations/failures and deal with them gracefully
• All about being a good programmer!
Module 12 : Exceptions 3
![Page 4: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/4.jpg)
What counts as an exception
• Errors: Indexing past the end of a list, trying to open a nonexistent file, fetching a nonexistent key from a dictionary, etc.
• Events: Search algorithm doesn’t find a value (not really an error), mail message arrives, queue event occurs.
• Ending conditions: File should be closed at the end of processing, list should be sorted after being filled.
• Weird stuff: For rare events, keep from clogging your code with lots of if statements.
Module 12 : Exceptions 4
![Page 5: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/5.jpg)
General idea
4 general steps:1. Keep watch on a particular section of code2. If we get an exception, raise/throw that
exception (let it be known)3. Look for a catcher that can handle that kind
of exception4. If found, handle it, otherwise let Python
handle it (which usually halts the program)
Module 12 : Exceptions 5
![Page 6: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/6.jpg)
Bad input
• In general, we have assumed that the input we receive is correct (from a file, from the user).
• This is almost never true. There is always the chance that the input could be wrong.
• Our programs should be able to handle this.• "Writing Secure Code,” by Howard and LeBlanc
– “All input is evil until proven otherwise.”
Module 12 : Exceptions 6
![Page 7: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/7.jpg)
General form v1
try:
Code to runexcept aParticularError:
Stuff to do on error
Module 12 : Exceptions 7
![Page 8: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/8.jpg)
Try suite
• The try suite contains code that we want to monitor for errors during its execution.
• If an error occurs anywhere in that try suite, Python looks for a handler that can deal with the error.
• If no special handler exists, Python handles it, meaning the program halts and with an error message as we have seen so many times
Module 12 : Exceptions
try: Code to run
8
![Page 9: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/9.jpg)
Except suite
• An except suite (perhaps multiple except suites) is associated with a trysuite.
• Each exception names a type of exception it is monitoring for (can handle).
• If the error that occurs in the try suite matches the type of exception, then that except suite is activated.
Module 12 : Exceptions
except aParticularError:Stuff to do on error
9
![Page 10: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/10.jpg)
try/except group
• If no exception in the try suite, skip all the try/except to the next line of code.
• If an error occurs in a try suite, look for the right exception.
• If found, run that except suite, and then skip past the try/except group to the next line of code.
• If no exception handling found, give the error to Python.
Module 12 : Exceptions 10
![Page 11: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/11.jpg)
Module 12 : Exceptions 11
![Page 12: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/12.jpg)
An exampletry:
print('Entering try suite') # tracedividend = float(input('dividend:'))divisor = float(input('divisor:'))result = dividend/divisor print('{:2.2f} divided by {:2.2f} = ’\
'{:2.2f}'.format(dividend,divisor,result))
except ZeroDivisionError:print('Divide by 0 error')
except ValueError:print("Couldn't convert to a float")
print('Continuing with the rest of the program')
Module 12 : Exceptions
Try Suite
Except Suite 1
Except Suite 1
Try/Except Group
12
![Page 13: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/13.jpg)
What exceptions are there?
• In the present Python, there is a set of exceptions that are pre‐labeled.
• To find the exception for a case you are interested in, easy enough to try it in the interpreter and see what comes up.
3/0 => ZeroDivisionError: integer division or modulo by zero
Module 12 : Exceptions 13
![Page 14: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/14.jpg)
Module 12 : Exceptions
Details: http://docs.python.org/library/exceptions.html14
![Page 15: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/15.jpg)
EXCEPTION PHILOSOPHYModule 12 : Exceptions
Module 12 : Exceptions 15
![Page 16: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/16.jpg)
How you deal with problems
Two ways to deal with exceptions:• LBYL: Look Before you Leap• EAFP: Easier to Ask Forgiveness than Permission (famous quote by Grace Hopper)
Module 12 : Exceptions 16
![Page 17: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/17.jpg)
Look before you leap
• Super cautious!• Check all aspects before executing
– If string required : check that– if values should be positive : check that
• What happens to length of code?• And readability of code – code is hidden in checking.
Module 12 : Exceptions 17
![Page 18: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/18.jpg)
Easier to ask forgiveness than permission
• Run anything you like!• Be ready to clean up in case of error.• The try suite code reflects what you want to do, and the except code what you want to do on error. Cleaner separation!
Module 12 : Exceptions 18
![Page 19: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/19.jpg)
A Choice
• Python programmers support the EAFP approach:– Run the code (in try) and used except suites to deal with errors (don’t check first)
Module 12 : Exceptions
if not isinstance(s, str) or not s.isdigit:return None
elif len(s) > 10: # too many digits to convertreturn None
else:return int(str)
try:return int(str)
except (TypeError, ValueError, OverflowError): return None
LBYL
EAFP
19
![Page 20: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/20.jpg)
OTHER SUITESModule 12 : Exceptions
Module 12 : Exceptions 20
![Page 21: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/21.jpg)
else suite
• The else suite is used to execute specific code when no exception occurs
Module 12 : Exceptions
try: Code to run
except aParticularError:Stuff to do on error
elseStuff to do when no error
21
![Page 22: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/22.jpg)
finally suite
• The finally suite is used to execute code at the end of try/except group (with or without error)
Module 12 : Exceptions
try: Code to run
except aParticularError:Stuff to do on error
finallyStuff to do always at end
22
![Page 23: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/23.jpg)
Challenge 12.1 Calculation errorsModify the calculator example from module 4 to capture some common exceptions.
Module 12 : Exceptions
ERROR!
23
![Page 24: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/24.jpg)
Thought process
• What errors can the code generate?• Capture the common ones and give clear instruction
• Use the else condition to print out answer only when no error
Module 12 : Exceptions 24
![Page 25: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/25.jpg)
Take home lessons
• Using exception handling to help users is important!
• Different types of exceptions: events, errors, etc.
• LYBL vs. EAFP• try‐except‐else‐finally suites (in many languages)
Module 12 : Exceptions 25
![Page 26: Lecture 12 exceptions](https://reader036.vdocument.in/reader036/viewer/2022081403/5551716ab4c9057e458b4a5f/html5/thumbnails/26.jpg)
Further reading
• http://docs.python.org/tutorial/errors.html
• http://diveintopython.org/file_handling/index.html
• http://oranlooney.com/lbyl‐vs‐eafp/
Module 12 : Exceptions 26