Post on 08-Sep-2020
Exception Handling SECTION 7.4
10/17/16 63
Exception Handling • Therearetwoaspectstodealingwithrun-4meprogramerrors:
1) Detec4ngErrors2) HandlingErrors
• Theopenfunc4oncandetectana>empttoreadfromanon-existentfile• Theopenfunc4oncannothandletheerror• Therearemul4plealterna4ves,thefunc4ondoesnotknowwhichisthecorrectchoice
• Thefunc4onreportstheerrortoanotherpartoftheprogramtobehandled
• Excep4onhandlingprovidesaflexiblemechanismforpassingcontrolfromthepointoftheerrortoahandlerthatcandealwiththeerror
10/17/16 Page 64
Detecting Errors • Whatdoyoudoifsomeonetriestowithdrawtoomuchmoneyfromabankaccount?
• Youcanraiseanexcep4on• Whenyouraiseanexcep4on,execu4ondoesnotcon4nuewiththenextstatement• Ittransferstotheexcep-onhandler
10/17/16
ifamount>balance:raiseValueError("Amountexceedsbalance")
Usetheraisestatementtosignalanexception
Page 65
Exception Classes (a subset) • Lookforanappropriateexcep4on
10/17/16 Page 66
Syntax: Raising an Exception
10/17/16 Page 67
Handling Exceptions • Everyexcep4onshouldbehandledsomewhereintheprogram• Thisisacomplexproblem
• Youneedtohandleeachpossibleexcep4onandreacttoitappropriately
• Handlingrecoverableerrorscanbedone:• Simply:exittheprogram• User-friendly:Asktheusertocorrecttheerror
10/17/16 Page 68
Handling Exceptions: Try-Except • Youhandleexcep4onswiththetry/exceptstatement
• Placethestatementintoaloca4onofyourprogramthatknowshowtohandleapar4cularexcep4on
• Thetryblockcontainsoneormorestatementsthatmaycauseanexcep4onofthekindthatyouarewillingtohandle
• Eachexceptclausecontainsthehandlerforanexcep4ontype
10/17/16 Page 69
Syntax: Try-Except
10/17/16 Page 70
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
Example • IfanIOErrorexcep4onisraised,theexceptclausefortheIOErrorexcep4onisexecuted
• IfaValueErrorexcep4onoccurs,thensecondexceptclauseisexecuted• Ifanyotherexcep4onisraiseditwillnotbehandledbyanyoftheexceptblocks
10/17/16 Page 72
Output Messages • Whenthebodyofthishandlerisexecuted,itprintsthemessageincludedwiththeexcep4on
10/17/16
exceptValueErrorasexception:print("Error:",str(exception))
Page 73
• Forexample,ifthestringpassedtotheint()func4onwas"35x2",thenthemessageincludedwiththeexcep4onwillbe:invalidliteralforint()withbase10:'35x2'
Output Messages (2) • Toobtainthemessage,wemusthaveaccesstotheexcep4onobjectitself
• Youcanstoretheexcep4onobjectinavariablewiththeassyntax:
10/17/16
exceptValueErrorasexception:
Page 74
• WhenthehandlerforValueErrorisexecuted,excep-onissettotheexcep4onobject.Inourcode,wethenobtainthemessagestringbycallingstr(excep-on)
Source of Output Messages • Whenyouraiseanexcep4on,youcanprovideyourownmessagestring.Forexample,whenyoucall
10/17/16
raiseValueError("Amountexceedsbalance")
Page 75
• Themessageoftheexcep4on,"Amountexceedsbalance",isthestringprovidedastheargumenttotheconstructor
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
Syntax: The Finally Clause
10/17/16 Page 77
Programming Tip • Throwexcep4onsearly
• Whenamethoddetectsaproblemthatitcannotsolve,itisbe>ertothrowanexcep4onratherthantrytocomeupwithanimperfectfix
• Catchexcep4onslate• Conversely,amethodshouldonlycatchanexcep4onifitcanreallyremedythesitua4on
• Otherwise,thebestremedyissimplytohavetheexcep4onpropagatetoitscaller,allowingittobecaughtbyacompetenthandler
10/17/16 Page 78
Programming Tip • Donotuseexceptandfinallyinthesametryblock
• Thefinallyclauseisexecutedwheneverthetryblockisexitedinanyofthreeways:1.A]ercomple4ngthelaststatementofthetryblock2.A]ercomple4ngthelaststatementofaexceptclause,ifthistryblockcaughtanexcep4on
3.Whenanexcep4onwasraisedinthetryblockandnothandled
10/17/16
try
except
finally
Page 79
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
The With Statement • Becauseatry/finallystatementforopeningandclosingfilesissocommon,Pythonhasaspecialshortcut:
10/17/16
withopen(filename,"w")asoutfile:Writeoutputtooutfile
Page 81
• Thiswithstatementopensthefilewiththegivenname,setsou_iletothefileobject,andclosesthefileobjectwhentheendofthestatementhasbeenreachedoranexcep4onisraised
Handling Input Errors SECTION 7.6
10/17/16 82
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
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
HandlingInputErrors:readFile()• CreatesthefileobjectandcallsthereadData()func4on• Noexcep4onhandling(noexceptclauses)• finallyclauseclosesfileinallcases(excep4onornot)
10/17/16
defreadFile(filename):inFile=open(filename,"r")#MaythrowexceptionstryreturnreadData(inFile)finallyin.close()
Page 85
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
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
Example Code • Openthefileanalyzedata.py
10/17/16 Page 88
Summary: File Input/Output • Whenopeningafile,yousupplythenameofthefilestoredondiskandthemodeinwhichthefileistobeopened
• Closeallfileswhenyouaredoneprocessingthem
• Usethereadline()methodtoobtainlinesoftextfromafile
• Writetoafileusingthewrite()methodortheprint()func4on
10/17/16 Page 89
Summary: Processing Text Files • Youcaniterateoverafileobjecttoreadthelinesoftextinthefile• Usetherstrip()methodtoremovethenewlinecharacterfromalineoftext
• Usethesplit()methodtosplitastringintoindividualwords
• Readoneormorecharacterswiththeread()method
10/17/16 Page 90
Command Line Arguments • Programsthatstartfromthecommandlinereceivethecommandlineargumentsintheargvlistdefinedinthesysmodule
10/17/16 Page 91
Summary: Exceptions (1) • Tosignalanexcep4onalcondi4on,usetheraisestatementtoraiseanexcep4onobject
• Whenyouraiseanexcep4on,processingcon4nuesinanexcep4onhandler
• Placethestatementsthatcancauseanexcep4oninsideatryblock,andthehandlerinsideanexceptclause
• Onceatryblockisentered,thestatementsinafinallyclauseareguaranteedtobeexecuted,whetherornotanexcep4onisraised
10/17/16 Page 92
Summary: Exceptions (2) • Raiseanexcep4onassoonasaproblemisdetected
• Handleitonlywhentheproblemcanbehandled
• Whendesigningaprogram,askyourselfwhatkindsofexcep4onscanoccur
• Foreachexcep4on,youneedtodecidewhichpartofyourprogramcancompetentlyhandleit
10/17/16 Page 93