lecture 12 exceptions
TRANSCRIPT
Introduction to computational thinking
Module 12 : Exceptions
Module 12 : Exceptions
Asst Prof Michael LeesOffice: N4‐02c‐76
email: mhlees[at]ntu.edu.sg1
Contents
1. Why & What are exceptions2. Try/Except group3. Exception Philosophy4. else and finally suites
Module 12 : Exceptions
Chapter 14
2
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
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
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
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
General form v1
try:
Code to runexcept aParticularError:
Stuff to do on error
Module 12 : Exceptions 7
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
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
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
Module 12 : Exceptions 11
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
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
Module 12 : Exceptions
Details: http://docs.python.org/library/exceptions.html14
EXCEPTION PHILOSOPHYModule 12 : Exceptions
Module 12 : Exceptions 15
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
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
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
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
OTHER SUITESModule 12 : Exceptions
Module 12 : Exceptions 20
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
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
Challenge 12.1 Calculation errorsModify the calculator example from module 4 to capture some common exceptions.
Module 12 : Exceptions
ERROR!
23
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
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
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