0321537904_ppt73679-0321537904_pptSavitch_ch_16_第1页
0321537904_ppt73679-0321537904_pptSavitch_ch_16_第2页
0321537904_ppt73679-0321537904_pptSavitch_ch_16_第3页
0321537904_ppt73679-0321537904_pptSavitch_ch_16_第4页
0321537904_ppt73679-0321537904_pptSavitch_ch_16_第5页
已阅读5页,还剩50页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Copyright2008PearsonAddison-Wesley.Allrightsreserved.,Chapter16,ExceptionHandling,Slide16-3,Overview,16.1Exception-HandlingBasics16.2ProgrammingTechniquesforExceptionHandling,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,16.1,Exception-HandlingBasics,Slide16-5,ExceptionHandlingBasics,ItisofteneasiertowriteaprogrambyfirstassumingthatnothingincorrectwillhappenOnceitworkscorrectlyfortheexpectedcases,addcodetohandletheexceptionalcasesExceptionhandlingiscommonlyusedtohandleerrorsituationsOnceanerrorishandled,itisnolongeranerror,Slide16-6,FunctionsandExceptionHandling,Acommonuseofexceptionhandling:FunctionswithaspecialcasethatishandledindifferentwaysdependingonhowthefunctionisusedIfthefunctionisusedindifferentprograms,eachprogrammayrequireadifferentactionwhenthespecialcaseoccurs,Slide16-7,ExceptionHandlingMechanism,InC+,exceptionhandlingproceedsby:SomelibrarysoftwareoryourcodesignalsthatsomethingunusualhashappenedThisiscalledthrowinganexceptionAtsomeotherplaceinyourprogramyouplacethecodethatdealswiththeexceptionalcaseThisiscalledhandlingtheexception,Slide16-8,AToyExample,ExceptionhandlingismeanttobeusedsparinglyinsituationsthataregenerallynotreasonableintroductoryexamplesForthisexample:SupposemilkissoimportantthatwealmostneverrunoutWestillwouldlikeourprogramtohandlethesituationofrunningoutofmilk,Slide16-9,TheMilkExample(cont.),Codetohandlethenormalsituationsinvolvingmilk,mightbe:coutdonuts;coutmilk;dpg=donuts/static_cast(milk);coutdonutsdonuts.nmilkglassesofmilk.nYouhavedpgdonutsperglassofmilk.n;,Slide16-10,Ifthereisnomilk,thecodeonthepreviousslideresultsinadivisionbyzeroWecouldaddatestcaseforthissituationshowstheprogramwiththetestcaseshowstheprogramrewrittenusinganexception,Display16.1,Display16.2(1-2),TheNoMilkProblem,Slide16-11,ThetryBlock,TheprogramofDisplay16.2replacesthetestcaseintheif-elsestatementwithif(milk=0)throwdonuts;ThiscodeisfoundinthetryblocktrySome_Codewhichenclosesthecodetohandlethenormalsituations,Slide16-12,TheTryBlockOutline,ThetryblockenclosescodethatyouwanttotrybutthatcouldcauseaproblemThebasicoutlineofatryblockis:tryCode_To_TryPossibly_Throw_An_ExceptionMore_Code,Slide16-13,TheException,Tothrowanexception,athrow-statementisusedtothrowavalueInthemilkexample:throwdonuts;throwsanintegervalue.ThevaluethrownissometimescalledanexceptionYoucanthrowavalueofanytype,Slide16-14,Thecatch-block,SomethingthatisthrowngoesfromoneplacetoanotherInC+throwcausestheflowofcontroltogotoanotherplaceWhenanexceptionisthrown,thetryblockstopsexecutingandthecatch-blockbeginsexecutionThisiscatchingorhandlingtheexception,Slide16-15,TheMilkcatch-block,Thecatch-blockfromthemilkexamplelookslike,butisnot,afunctiondefinitionwithaparameter:catch(inte)coutedonuts,andnomilk!nGobuysomemilk.n;Ifnoexceptionisthrown,thecatch-blockisignoredduringprogramexecution,Slide16-16,Thecatch-blockParameter,Thecatch-blockparameter,(recallthatthecatch-blockisnotafunction)doestwothings:Thetypeofthecatch-blockparameteridentifiesthekindofvaluethecatch-blockcancatchThecatch-blockparameterprovidesanameforthevaluecaughtsoyoucanwritecodeusingthevaluethatiscaught,Slide16-17,try-blocksandif-else,try-blocksareverysimilartoif-elsestatementsIfeverythingisnormal,theentiretry-blockisexecutedelse,ifanexceptionisthrown,thecatch-blockisexecutedAbigdifferencebetweentry-blocksandif-elsestatementsisthetry-blocksabilitytosendamessagetooneofitsbranches,Slide16-18,try-throw-catchReview,ThisisthebasicmechanismforthrowingandcatchingexceptionsThetry-blockincludesathrow-statementIfanexceptionisthrown,thetry-blockendsandthecatch-blockisexecutedIfnoexceptionisthrown,thenafterthetry-blockiscompleted,executioncontinueswiththecodefollowingthecatch-block(s),Slide16-19,DefininganExceptionClass,Becauseathrow-statementcanthrowavalueofanytype,itiscommontodefineaclasswhoseobjectscancarrythekindofinformationyouwantthrowntothecatch-blockAmoreimportantreasonforaspecializedexceptionclassissoyoucanhaveadifferenttypetoidentifyeachpossiblekindofexceptionalsituation,Slide16-20,AnexceptionclassisjustaclassthathappenstobeusedasanexceptionclassAnexampleofaprogramwithaprogrammerdefinedexceptionclassisin,Display16.3(1-2),TheExceptionClass,Slide16-21,ThrowingaClassType,TheprograminDisplay16.3usesthethrow-statementthrowNoMilk(donuts);ThisinvokesaconstructorfortheclassNoMilkTheconstructortakesasingleargumentoftypeintTheNoMilkobjectiswhatisthrownThecatch-blockthenusesthestatemente.get_donuts()toretrievethenumberofdonuts,Slide16-22,Atry-blockcanthrowanynumberofexceptionsofdifferenttypesInanyoneexecution,onlyoneexceptioncanbethrownEachcatch-blockcancatchonlyoneexceptionMultiplecatch-blocksmaybeusedAparameterisnotrequiredinacatch-blockAsampleprogramwithtwocatch-blocksisfoundin,Display16.4(1-3),MultipleThrowsandCatches,Slide16-23,ADefaultcatch-block,Whencatchingmultipleexceptions,writethecatch-blocksforthemostspecificexceptionsfirstCatch-blocksaretriedinorderandthefirstonematchingthetypeofexceptionisexecutedAdefault(andlast)catch-blocktocatchanyexceptioncanbemadeusingasthecatch-blockparametercatch(),Slide16-24,ExceptionClassDivideByZero,InDisplay16.4,exceptionclassDivideByZerowasdefinedasclassDivideByZero;ThisclasshasnomembervariablesormemberfunctionsThisisatrivialexceptionclassDivideByZeroisusedsimplytoactivatetheappropriatecatch-blockThereisnothingtodowiththecatch-blockparametersoitcanbeomittedasshowninDisplay16.4,Slide16-25,ExceptionsInFunctions,Insomecases,anexceptiongeneratedinafunctionisnothandledinthefunctionItmightbethatsomeprogramsshouldend,whileothersmightdosomethingelse,sowithinthefunctionyoumightnotknowhowtohandletheexceptionInthiscase,theprogramplacesthefunctioninvocationinatryblockandcatchestheexceptioninafollowingcatch-block,Slide16-26,Functionsafe_divide,TheprogramofDisplay16.5includesafunctionthatthrows,butdoesnotcatchanexceptionInfunctionsafe_divide,thedenominatorischeckedtobesureitisnotzero.Ifitiszero,anexceptionisthrown:if(bottom=0)throwDivideByZero();Thecalltofunctionsafe_divideisfoundinthetry-blockoftheprogram,IfafunctiondoesnotcatchanexceptionitshouldwarnprogrammersthananexceptionmightbethrownbythefunctionAnexceptionspecification,alsocalledathrowlist,appearsinthefunctiondeclarationanddefinition:doublesafe_divide(intn,intd)throw(DivideByZero);ifmultipleexceptionsarethrownandnotcaughtbyafunction:doublesafe_divide(intn,intd)throw(DivideByZero,OtherException);,Slide16-27,Display16.5(1-2),ExceptionSpecification,Slide16-28,ExceptionsNotListed,Ifanexceptionisnotlistedinanexceptionspecificationandnotcaughtbythefunction:TheprogramendsIfthereisnoexceptionspecificationatall,itisthesameasifallpossibleexceptionsarelistedTheseexceptionswillbetreatednormallyAnemptyexceptionspecificationlistmeansthatnoexceptionsshouldbethrownandnotcaught,Slide16-29,SampleExceptionSpecifications,voidsome_function()throw();/emptyexceptionlist;soallexceptionsnot/caughtbythefunctionendtheprogramvoidsome_function()throw(DivideByZero,OtherException);/ExceptionsDivideByZeroandOtherException/treatednormally.Allothersendtheprogramvoidsome_function();/Allexceptionsofalltypestreatednormally/Ifnotcaughtbyacatch-block,theprogramends,Slide16-30,DerivedClassesandExceptions,RememberthatanobjectofaderivedclassisalsoanobjectofthebaseclassIfDisaderivedclassofBandBisinanexceptionspecificationAthrownobjectofclassDwillbetreatednormallysinceitisanobjectofclassB,Slide16-31,TypeConversion,Noautomatictypeconversionsaredonewithexceptionsifdoubleisintheexceptionspecification,anintcannotbethrownunlessintisalsointheexceptionspecification,Slide16-32,FunctionRedefinitionsinDerivedClasses,FunctionsredefinedoroverloadedinderivedclassesshouldhavethesameexceptionspecificationasinthebaseclassTheexceptionspecificationcanbeasubsetoftheexceptionspecificationinthebaseclassYoucannotaddexceptions,Slide16-33,Section16.1Conclusion,CanyouListthethreecomponentsofexceptionhandling?Writecodetocatchanexceptionoftypechar?Createanexceptionspecificationforafunction?Createanexceptionclass?,Copyright2008PearsonAddison-Wesley.Allrightsreserved.,16.2,ProgrammingTechniquesforException-Handling,Slide16-35,ProgrammingTechniquesforExceptionHandling,AguidelineforexceptionhandlingistoseparatethrowinganexceptionandcatchinganexceptionintoseparatefunctionsPlacethethrow-statementinonefunctionandlisttheexceptionintheexceptionspecificationPlacethefunctioninvocationandcatch-clauseinatry-blockofadifferentfunction,Slide16-36,tryandthrowAgain,Hereisageneralexampletheapproachtouseinusingthrow:voidfunctionA()throw(MyException)throwMyException();,Slide16-37,catchagain,UsingFunctionAfromthepreviousslide,hereishowtocatchMyException:voidfunctionB()tryfunctionA();catch(MyExceptione),Slide16-38,WhentoThrowAnException,ThrowingexceptionsisgenerallyreservedforthosecaseswhenhandlingtheexceptionalcasedependsonhowandwherethefunctionwasinvokedInthesecasesitisusuallybesttolettheprogrammercallingthefunctionhandletheexceptionAnuncaughtexceptionendsyourprogramIfyoucaneasilywritecodetohandletheproblemdonotthrowanexception,Slide16-39,Nestedtry-catchBlocks,Althoughatry-blockfollowedbyitscatch-blockcanbenestedinsideanothertry-blockItisalmostalwaysbettertoplacethenestedtry-blockanditscatch-blockinsideafunctiondefinition,theninvokethefunctionintheoutertry-blockAnerrorthrownbutnotcaughtintheinnertry-catch-blocksisthrowntotheoutertry-blockwhereitmightbecaught,Slide16-40,OveruseofExceptions,ThrowinganexceptionallowsyoutotransferflowofcontroltoalmostanyplaceinyourprogramSuchun-restrictedflowofcontrolisgenerallyconsideredpoorprogrammingstyleasitmakesprogramsdifficulttounderstandExceptionsshouldbeusedsparinglyandonlywhenyoucannotcomeupwithanalternativethatproducesreasonablecode,Slide16-41,ExceptionClassHierarchies,Itcanbeusefultodefineahierarchyofexceptionclasses.YoumighthaveanArithmeticErrorexceptionclasswithDivideByZeroErrorasaderivedclassSinceaDivideByZeroErrorobjectisalsoanArithmeticErrorobject,everycatch-bl

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论