Exception Handling · The finally Clause • The finally clause is used when you need to take some...

31
Exception Handling SECTION 7.4 10/17/16 63

Transcript of Exception Handling · The finally Clause • The finally clause is used when you need to take some...

Page 1: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Exception Handling SECTION 7.4

10/17/16 63

Page 2: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Exception Handling •  Therearetwoaspectstodealingwithrun-4meprogramerrors:

1)  Detec4ngErrors2)  HandlingErrors

•  Theopenfunc4oncandetectana>empttoreadfromanon-existentfile•  Theopenfunc4oncannothandletheerror•  Therearemul4plealterna4ves,thefunc4ondoesnotknowwhichisthecorrectchoice

•  Thefunc4onreportstheerrortoanotherpartoftheprogramtobehandled

•  Excep4onhandlingprovidesaflexiblemechanismforpassingcontrolfromthepointoftheerrortoahandlerthatcandealwiththeerror

10/17/16 Page 64

Page 3: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Detecting Errors •  Whatdoyoudoifsomeonetriestowithdrawtoomuchmoneyfromabankaccount?

•  Youcanraiseanexcep4on•  Whenyouraiseanexcep4on,execu4ondoesnotcon4nuewiththenextstatement•  Ittransferstotheexcep-onhandler

10/17/16

ifamount>balance:raiseValueError("Amountexceedsbalance")

Usetheraisestatementtosignalanexception

Page 65

Page 4: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Exception Classes (a subset) •  Lookforanappropriateexcep4on

10/17/16 Page 66

Page 5: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Syntax: Raising an Exception

10/17/16 Page 67

Page 6: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Handling Exceptions •  Everyexcep4onshouldbehandledsomewhereintheprogram•  Thisisacomplexproblem

•  Youneedtohandleeachpossibleexcep4onandreacttoitappropriately

•  Handlingrecoverableerrorscanbedone:•  Simply:exittheprogram•  User-friendly:Asktheusertocorrecttheerror

10/17/16 Page 68

Page 7: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Handling Exceptions: Try-Except •  Youhandleexcep4onswiththetry/exceptstatement

•  Placethestatementintoaloca4onofyourprogramthatknowshowtohandleapar4cularexcep4on

•  Thetryblockcontainsoneormorestatementsthatmaycauseanexcep4onofthekindthatyouarewillingtohandle

•  Eachexceptclausecontainsthehandlerforanexcep4ontype

10/17/16 Page 69

Page 8: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Syntax: Try-Except

10/17/16 Page 70

Page 9: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Try-Except: An Example

10/17/16

try:filename=input("Enterfilename:")infile=open(filename,"r")line=infile.readline()value=int(line)...exceptIOError:print("Error:filenotfound.")exceptValueErrorasexception:print("Error:",str(exception))

Executiontransfershereiffilecannotbeopened

int()canraiseaValueErrorexcep4on

open()canraiseanIOErrorexcep4on

Executiontransfershere

ifthestringcannotbeconvertedtoanint

Ifeitheroftheseexcep.onsisraised,therestoftheinstruc.onsinthetry

blockareskipped

Page 71

Page 10: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Example •  IfanIOErrorexcep4onisraised,theexceptclausefortheIOErrorexcep4onisexecuted

•  IfaValueErrorexcep4onoccurs,thensecondexceptclauseisexecuted•  Ifanyotherexcep4onisraiseditwillnotbehandledbyanyoftheexceptblocks

10/17/16 Page 72

Page 11: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Output Messages •  Whenthebodyofthishandlerisexecuted,itprintsthemessageincludedwiththeexcep4on

10/17/16

exceptValueErrorasexception:print("Error:",str(exception))

Page 73

•  Forexample,ifthestringpassedtotheint()func4onwas"35x2",thenthemessageincludedwiththeexcep4onwillbe:invalidliteralforint()withbase10:'35x2'

Page 12: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Output Messages (2) •  Toobtainthemessage,wemusthaveaccesstotheexcep4onobjectitself

•  Youcanstoretheexcep4onobjectinavariablewiththeassyntax:

10/17/16

exceptValueErrorasexception:

Page 74

•  WhenthehandlerforValueErrorisexecuted,excep-onissettotheexcep4onobject.Inourcode,wethenobtainthemessagestringbycallingstr(excep-on)

Page 13: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Source of Output Messages •  Whenyouraiseanexcep4on,youcanprovideyourownmessagestring.Forexample,whenyoucall

10/17/16

raiseValueError("Amountexceedsbalance")

Page 75

•  Themessageoftheexcep4on,"Amountexceedsbalance",isthestringprovidedastheargumenttotheconstructor

Page 14: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

The finally Clause •  Thefinallyclauseisusedwhenyouneedtotakesomeac4onwhetherornotanexcep4onisraised

•  Hereisatypicalsitua4on•  Itisimportanttoalwayscloseanoutputfilewhetherornotanexcep4onwasraised(toensurethatalloutputiswri>entothefile)

•  Placethecalltoclose()insideafinallyclause:

10/17/16

outfile=open(filename,"w")try:writeData(outfile)finally:outfile.close()

Page 76

Page 15: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Syntax: The Finally Clause

10/17/16 Page 77

Page 16: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Programming Tip •  Throwexcep4onsearly

•  Whenamethoddetectsaproblemthatitcannotsolve,itisbe>ertothrowanexcep4onratherthantrytocomeupwithanimperfectfix

•  Catchexcep4onslate•  Conversely,amethodshouldonlycatchanexcep4onifitcanreallyremedythesitua4on

•  Otherwise,thebestremedyissimplytohavetheexcep4onpropagatetoitscaller,allowingittobecaughtbyacompetenthandler

10/17/16 Page 78

Page 17: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Programming Tip •  Donotuseexceptandfinallyinthesametryblock

•  Thefinallyclauseisexecutedwheneverthetryblockisexitedinanyofthreeways:1.A]ercomple4ngthelaststatementofthetryblock2.A]ercomple4ngthelaststatementofaexceptclause,ifthistryblockcaughtanexcep4on

3.Whenanexcep4onwasraisedinthetryblockandnothandled

10/17/16

try

except

finally

Page 79

Page 18: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Programming Tip •  Itisbe>ertousetwo(nested)tryclausestocontroltheflow

10/17/16

try

except

finally

try:outfile=open(filename,"w")try:#Writeoutputtooutfilefinally:out.close()#CloseresourcesexceptIOError:#Handleexception

try

Page 80

Page 19: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

The With Statement •  Becauseatry/finallystatementforopeningandclosingfilesissocommon,Pythonhasaspecialshortcut:

10/17/16

withopen(filename,"w")asoutfile:Writeoutputtooutfile

Page 81

•  Thiswithstatementopensthefilewiththegivenname,setsou_iletothefileobject,andclosesthefileobjectwhentheendofthestatementhasbeenreachedoranexcep4onisraised

Page 20: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Handling Input Errors SECTION 7.6

10/17/16 82

Page 21: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Handling Input Errors •  FileReadingApplica4onExample

•  Goal:Readafileofdatavalues•  Firstlineisthecountofvalues•  Remaininglineshavevalues

•  Risks:•  Thefilemaynotexist

•  Theopen()func4onwillraiseanexcep4onwhenthefiledoesnotexist

•  Thefilemighthavedatainthewrongformat•  Whentherearefewerdataitemsthanexpected,orwhenthefiledoesn’tstartwiththecountofvalues,theprogramwillraiseaValueErrorexcep4on

•  Finally,whentherearemoreinputsthanexpected,aRun4meErrorexcep4onshouldberaised

10/17/16

3 1.45 -2.1 0.05

Page 83

Page 22: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Handling Input Errors: main() •  Outlineformethodwithallexcep4onhandling

10/17/16

done=Falsewhilenotdone:try:#Promptuserforfilenamedata=readFile(filename)#Mayraiseexceptions#Processdatadone=true;exceptIOError:print("Filenotfound.")exceptValueError:print("Filecontentsinvalid.")exceptRuntimeErroraserror:print("Error:",str(error))

Page 84

Page 23: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

HandlingInputErrors:readFile()•  CreatesthefileobjectandcallsthereadData()func4on•  Noexcep4onhandling(noexceptclauses)•  finallyclauseclosesfileinallcases(excep4onornot)

10/17/16

defreadFile(filename):inFile=open(filename,"r")#MaythrowexceptionstryreturnreadData(inFile)finallyin.close()

Page 85

Page 24: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Handling Input Errors: readData()•  Noexcep4onhandling(notryorexceptclauses)•  raisecreatesanValueErrorexcep4onandexits•  Run4meErrorexcep4oncanoccur

10/17/16

defreadData(inFile):line=inFile.readline()numberOfValues=int(line)#MayraiseaValueErrorexception.data=[]foriinrange(numberOfValues):line=inFile.readline()value=int(line)#MayraiseaValueErrorexception.data.append(value)#Makesuretherearenomorevaluesinthefile.line=inFile.readline()#Extradatainfileifline!="":raiseRuntimeError("Endoffileexpected.")returndata

Page 86

Page 25: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

One Scenario 1. maincallsreadFile

2. readFilecallsreadData

3. readDatacallsint4. Thereisnointegerintheinput,andintraisesaValueErrorexcep4on

5. readDatahasnoexceptclause;itterminatesimmediately

6. readFilehasnoexceptclause;itterminatesimmediatelya]erexecu4ngthefinallyclauseandclosingthefile

7. TheIOErrorexceptclauseisskipped8. TheValueErrorexceptclauseisexecuted

10/17/16 Page 87

Page 26: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Example Code •  Openthefileanalyzedata.py

10/17/16 Page 88

Page 27: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Summary: File Input/Output •  Whenopeningafile,yousupplythenameofthefilestoredondiskandthemodeinwhichthefileistobeopened

•  Closeallfileswhenyouaredoneprocessingthem

•  Usethereadline()methodtoobtainlinesoftextfromafile

•  Writetoafileusingthewrite()methodortheprint()func4on

10/17/16 Page 89

Page 28: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Summary: Processing Text Files •  Youcaniterateoverafileobjecttoreadthelinesoftextinthefile•  Usetherstrip()methodtoremovethenewlinecharacterfromalineoftext

•  Usethesplit()methodtosplitastringintoindividualwords

•  Readoneormorecharacterswiththeread()method

10/17/16 Page 90

Page 29: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Command Line Arguments •  Programsthatstartfromthecommandlinereceivethecommandlineargumentsintheargvlistdefinedinthesysmodule

10/17/16 Page 91

Page 30: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Summary: Exceptions (1) •  Tosignalanexcep4onalcondi4on,usetheraisestatementtoraiseanexcep4onobject

•  Whenyouraiseanexcep4on,processingcon4nuesinanexcep4onhandler

•  Placethestatementsthatcancauseanexcep4oninsideatryblock,andthehandlerinsideanexceptclause

•  Onceatryblockisentered,thestatementsinafinallyclauseareguaranteedtobeexecuted,whetherornotanexcep4onisraised

10/17/16 Page 92

Page 31: Exception Handling · The finally Clause • The finally clause is used when you need to take some ac4on whether or not an excep4on is raised • Here is a typical situaon

Summary: Exceptions (2) •  Raiseanexcep4onassoonasaproblemisdetected

•  Handleitonlywhentheproblemcanbehandled

•  Whendesigningaprogram,askyourselfwhatkindsofexcep4onscanoccur

•  Foreachexcep4on,youneedtodecidewhichpartofyourprogramcancompetentlyhandleit

10/17/16 Page 93