版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
ExceptionHandling1OutlineIntroductionJavaExceptionsManchesterUniversity,Kung-KiuLau,CS3101源自http://www.cs.man.ac.uk/~kung-kiu/cs3101/JavaException机制旳不当使用示例C++Exceptions/~ingber/SNL/CS162/PowerPoint/Session12and13.pptEiffelExceptionHandlingSummary2简介问题何谓“异常(Exception)”?一种情况要异常到什么程度才算“异常”?为何要引入异常处理机制?Robustnessreadability?怎样进行异常处理?MandatoryorOptional不同旳认识,不同旳答案Java/C++/C#Eiffel3JavaExceptionMechanismsJava对Exception旳界定较宽因而需仔细区别不同类型旳ExceptionsJava旳Exception机制回忆try/catch/finally自定义ExceptionsJavaException与DesignbyContractException旳转换4UnderstandingJavaExceptions这部分使用ManchesterUniversity,Kung-KiuLau,CS3101旳PPTSlides源自http://www.cs.man.ac.uk/~kung-kiu/cs3101/5WhatareExceptions?Many“exceptional”thingscanhappenduringtherunningofaprogram,e.g.:
Bugintheactuallanguageimplementation
Usermis-typesinput
Webpagenotavailable
Filenotfound
Dividebyzero
Arrayindexoutofbounds
Methodcalledonanullobject
OutofmemoryExceptionsareunexpectedconditionsinprograms.checkeduncheckedsyserrors6Wecandistinguish3categories:
checkedexceptions—Problemstodowiththeprogram'sinteractionwith“theworld”.
uncheckedexceptions—Problemswithintheprogramitself(i.e.violationsofthecontract,orbugs).
systemerrors
—Problemswiththeunderlyingsystem.Theseareoutsideourcontrol.Theworldisunpredictable,sowewouldexpectthesethingstohappeninproductioncode,andsoneedtohandlethem.Theseshouldberemovedbytesting,andnotoccurinproductioncode.UncheckedExceptionsSystemErrorsProgramSystemTheWorldCheckedExceptions7CheckedvsUncheckedExceptionsUncheckedExceptionsSystemErrorsProgramSystemTheWorldCheckedExceptionsanimportantdistinction,whichtheJavaExceptionclasshierarchydoesmake,butinaratherconfusingwaywewouldnormallycheckforthese,anddealwiththemwhentheyoccur.it'snormaltoletthesejustcrashtheprogramsowecandebugit.Exceptionhandlingisthebusinessofhandlingthesethingsappropriately.8ExceptionHierarchyinJavaThrowableExceptionRunTimeExceptionError...UncheckedExceptionsSystemErrorsProgramSystemTheWorldCheckedExceptionsErrorRunTimeExceptionException
RunTimeException9Whatdowewantofexceptions?Ideally,alanguage(anditsimplementation)should:
Restrictthesetofpossibleexceptionsto“reasonable”ones
Indicatewheretheyhappened,anddistinguishbetweentheme.g.nopointerstodeallocatedmemoryandnotmapthemallto“buserror”etc.
Allowexceptionstobedealtwithinadifferentplaceinthecodefromwheretheyoccursonormalcasecodecanbewrittencleanlywithouthavingtoworryaboutthemsowethrowexceptionswheretheyoccur,andcatchthemwherewewanttodealwiththem.Ideally,wedon'twantnon-fatalexceptionstobethrowntoofar—thisbreaksupthemodularityoftheprogramandmakesithardtoreasonabout.10ExceptionsinJava—areminderInJava,thebasicexceptionhandlingconstructisto:Ifathrownexceptionisnotcaught,itpropagatesouttothecallerandsoonuntilmain.Ifamethodcangenerate(checked)exceptionsbutdoesnothandlethem,ithastoexplicitlydeclarethatitthrowsthemsothatclientsknowwhattoexpect.
finallydoanythingwewanttodoirrespectiveofwhathappenedbefore.
catch
anyexceptionsthatitgenerates,andIfitisnevercaught,itterminatestheprogram.
try
ablockofcodewhichnormallyexecutesok11ExamplepublicclassEtest{publicstaticvoidmain(Stringargs[]){//WhatweexpecttohappenSystem.out.println(x+"/"+y+"="+x/y);}try{intx=Integer.parseInt(args[0]);inty=Integer.parseInt(args[1]);catch(NumberFormatExceptione){//Thingswhichcangowrongcatch(IndexOutOfBoundsExceptione){System.out.println("Usage:Etest<int><int>");}System.out.println(e.getMessage()+"isnotanumber");}//Dothisregardlessfinally{System.out.println("That'sall,folks");}}//main}//Etest12publicclassEtest{publicstaticvoidmain(Stringargs[]){//WhatweexpecttohappenSystem.out.println(x+"/"+y+"="+x/y);}try{intx=Integer.parseInt(args[0]);inty=Integer.parseInt(args[1]);catch(NumberFormatExceptione){//Thingswhichcangowrongcatch(IndexOutOfBoundsExceptione){System.out.println("Usage:Etest<int><int>");}System.out.println(e.getMessage()+"isnotanumber");}//Dothisregardlessfinally{System.out.println("That'sall,folks");}}//main}//Etest>javaEtest994299/42=2That'sall,folks13publicclassEtest{publicstaticvoidmain(Stringargs[]){//WhatweexpecttohappenSystem.out.println(x+"/"+y+"="+x/y);}try{intx=Integer.parseInt(args[0]);inty=Integer.parseInt(args[1]);catch(NumberFormatExceptione){//Thingswhichcangowrongcatch(IndexOutOfBoundsExceptione){System.out.println("Usage:Etest<int><int>");}System.out.println(e.getMessage()+"isnotanumber");}//Dothisregardlessfinally{System.out.println("That'sall,folks");}}//main}//Etest>javaEtest99Usage:Etest<int><int>That'sall,folks14publicclassEtest{publicstaticvoidmain(Stringargs[]){//WhatweexpecttohappenSystem.out.println(x+"/"+y+"="+x/y);}try{intx=Integer.parseInt(args[0]);inty=Integer.parseInt(args[1]);catch(NumberFormatExceptione){//Thingswhichcangowrongcatch(IndexOutOfBoundsExceptione){System.out.println("Usage:Etest<int><int>");}System.out.println(e.getMessage()+"isnotanumber");}//Dothisregardlessfinally{System.out.println("That'sall,folks");}}//main}//Etest>javaEtest99fredfredisnotanumberThat'sall,folks15publicclassEtest{publicstaticvoidmain(Stringargs[]){//WhatweexpecttohappenSystem.out.println(x+"/"+y+"="+x/y);}try{intx=Integer.parseInt(args[0]);inty=Integer.parseInt(args[1]);catch(NumberFormatExceptione){//Thingswhichcangowrongcatch(IndexOutOfBoundsExceptione){System.out.println("Usage:Etest<int><int>");}System.out.println(e.getMessage()+"isnotanumber");}//Dothisregardlessfinally{System.out.println("That'sall,folks");}}//main}//Etest>javaEtestfredfredisnotanumberThat'sall,folks16publicclassEtest{publicstaticvoidmain(Stringargs[]){//WhatweexpecttohappenSystem.out.println(x+"/"+y+"="+x/y);}try{intx=Integer.parseInt(args[0]);inty=Integer.parseInt(args[1]);catch(NumberFormatExceptione){//Thingswhichcangowrongcatch(IndexOutOfBoundsExceptione){System.out.println("Usage:Etest<int><int>");}System.out.println(e.getMessage()+"isnotanumber");}//Dothisregardlessfinally{System.out.println("That'sall,folks");}}//main}//Etest>javaEtest990That'sall,folksjava.lang.ArithmeticException:/byzeroatEtest.main(Etest.java:8)17UsingfinallyforCleanupFinalizersaren'tmuchgoodforreleasingresourcesTogetguaranteedcleanupofnetworkconnectionsetc.usefinallyclauses,e.g.:becausewedon'tknowwhen(orevenif)theywillbecalledButthere'sasnag—thecalltoin.close()mayitselfthrowanexceptione.g.ifthenetworkgoesdownatthewrongmomentSoweactuallyneedatry
...
catchblockwithinthefinallyclauseSockets;InputStreamin;try{s=newSocket(...);...in=s.getInputStream();...catch(IOExceptione){...}}finally{if(in!=null)in.close());s.close();}
s.close();finally{try{if(in!=null)in.close());}}catch(IOExceptione){}18CreatingandThrowingYourOwnExceptionsYoucancreateyourownexceptionclassesbyinheritingfromthestandardones.classUnhappyWidgetExceptionextendsException{publicUnhappyWidgetException(Widgetw){super(w.getProblem());}E.g.Whentherelevantproblemisdetected,youcreateanexceptionandthrowit.Theconstructorshouldcallthesuperclassconstructorwithastringtoindicatewhatwentwrong19Ifit'snothandledwithinthesamemethod,youneedtodeclarethatthemethodthrowstheexceptionif(wig.isHappy()){...}elsethrow(newUnhappyWidgetException(wig));}NotethefreedomwhichGCgivesus:wheneverweneedanewthingy(UnhappyWidgetException)wejustmakeonewedon'thavetoworryaboutwhenwewillbeabletoreclaimthememory.andlikewiseformethodswhichcallthatmethod,andmethodswhichcallthosemethods...E.g.publicvoidwidgetTest(Widgetwig)throwsUnhappyWidgetException{20TheThrowableClassHierarchyThestandardAPIdefinesmanydifferentexceptiontypes
basiconesinjava.lang
othersinotherpackages,especiallyjava.ioThrowableExceptionRunTimeExceptionError...Toplevelclassisnot
ExceptionbutThrowable.21Ingeneral,youwanttocatchspecificsortsof(checked)exceptions,andsayingcatch(Exceptione)isbadstyle.ThrowableExceptionRunTimeExceptionError...ProblemswiththeunderlyingJavaplatform,e.g.VirtualMachineError.UsercodeshouldneverexplicitlygenerateErrors.ThisisnotalwaysfollowedintheJavaAPI,andyoumayoccasionallyneedtosaycatch(Throwablee)todetectsomebizarreerrorconditionnevermindThrowable!22ItwouldbemuchclearerifthiswascalledUncheckedExceptionTheseincludeouroldfriendsNullPointerExceptionandArrayIndexOutOfBoundsException.Virtuallyanymethodcaninprinciplethrowoneormoreofthese,sothere'snorequirementtodeclaretheminthrows
clauses.ThrowableExceptionRunTimeExceptionError...UncheckedexceptionsaresubclassesofRuntimeException23Ifyouwritecodewhichcanthrowoneofthese,youmusteithercatchitordeclarethatthemethodthrows
it.ItwouldbeniceiftherewasaclassCheckedException.ThrowableExceptionRunTimeExceptionError...AllotherexceptionsarecheckedexceptionsThemostcommononesareIOExceptionssuchasFileNotFoundException.Thecompilergoestoenormouslengthstoenforcethis,andrelatedconstraints,e.g.thatalloverriddenversionsofamethodhaveconsistentthrowsclauses.24ExceptionHandlingandDbCDbCisaboutstaticallydefiningtheconditionsunderwhichcodeissupposedtooperate.
UncheckedexceptionsareExceptionsareaboutdealingwiththingsgoingwrongatruntime.(Thetwoarenicelycomplementary.)
Checkedexceptionsareexpectedtohappenfromtimetotimee.g.ifapreconditionthatanarrayhasatleastoneelementisbroken,anArrayIndexOutOfBoundsException
willprobablyoccur.“whathappenswhenthecontractisbroken”soarenotcontractviolations.25
codewhichreliesontheinputbeingcorrecttoprocessitSoifwe'regoingtouseDbC,weoughttostructureourcodeinto:
codewhichdealswithTheWorld
codewhichisinsulatedfromTheWorld.E.g.anapplicationinvolvingform-fillingshouldhaveMethodsdoingthiswillhaveno(orweak)preconditions,andwilldealwithproblemsviaexceptionhandling.Thiscanhavestrongpreconditionsandwon'tthrowexceptions(apartfromuncheckedonesduringdebugging).
codewhichvalidatestheuserinputfortype-correctnessetc.Ifthesetwosortsofoperationsaremixedtogether,theapplicationwillprobablybehardertomaintainandmoreerror-prone.26ConvertingExceptionsGoodOOdesigndecouplesthings.E.g.inmostpatternsthere'saClient
classwhichdelegatesoperationstosome“blackbox”inthepattern.ClientBlackboxopWhathappensiftheblackboxthrowsa(checked)exception?someapplication-specificcodesomeapplication-independentlibrarymayhaveitsownexceptiontypes,buttheyneedtobeapplication-specific.exceptionsthrownfromwithinthelibrarywillbeapplication-independent.Thetrickistoconvertfromtheformertothelatter.27ApplicationSpecificExceptionwillthereforehaveaconstructorwhichtry{...obj.delegateOp(...);...}catch(ApplicationIndependentExceptione){thrownewApplicationSpecificException(e);}
extractstherelevantinformationandre-castsitinapplication-specificterms.
takesanApplicationIndependentException28ExampleConsideracompilerforanoolanguageIfsomethinggoeswronginbuildingorusingaHierarchyanInvalidHierarchyExceptionisthrown.Thekeyistheclassnameandthevalueisthedefinitionoftheclass.
Ifthisoccurswhiletheclasshierarchyisbeingbuilt,itmeanstheuserhasmis-speltaclassnameorwhatever.Insuchacompiler,it'susefultohaveanexplicitrepresentationoftheinheritancehierarchyofthesourceprogramasatree(orgraph).e.g.anodehasnoparent,orthere'sacycleTheInvalidHierarchyExcetpionisconvertedtoa(checked)IllegalInheritanceExceptionresultinginasuitableerrormessagebeingdisplayedtotheuser.
Ifithappenslater,an(unchecked)CompilerBrokenExpectionisthrowninstead,becauseitmeansthere'sabuginthecompiler.whichhasanapplication-independent
Hierarchy
classwhichrepresentsahierarchyofarbitrarykey-valuepairs.29Summary
Exceptionhandlingisanimportant,highlyintegrated,partoftheJavasystem,oneoftheReallyNeatThingsAboutJava.
Checkedexceptionshappenwhentheprogram'sinteractionwiththeworlddepartsfromthenormalcase.Makesureyouhandlethemappropriately.
Uncheckedexceptionsroutinelyoccurduringdebugging,andmakethatprocessmucheasier.Byproductshippingtime,theyshouldnolongeroccur.Inparticular,thinkhardaboutwheretohandleanexception,soastosimplifythenormal-casecode,butnottodothehandlingsofarawaythatmodularityiscompromised.
Application-independentexceptionsneedtobeconvertedtoapplication-specificones.30JavaExceptionJavaException机制旳不当使用:引自网络论坛:311
OutputStreamWriter
out
=
...
2
java.sql.Connection
conn
=
...
3
try
{
//
⑸
4
Statement
stat
=
conn.createStatement();
5
ResultSet
rs
=
stat.executeQuery(
6
"select
uid,
name
from
user");
7
while
(rs.next())
8
{
9
out.println("ID:"
+
rs.getString("uid")
//
⑹
10
",姓名:"
+
rs.getString("name"));
11
}
12
conn.close();
//
⑶
13
out.close();
14
}
15
catch(Exception
ex)
//
⑵
16
{
17
ex.printStackTrace();
//⑴,⑷
18
}32问题丢弃异常不指定详细旳异常占用资源不释放不阐明异常旳详细信息过于庞大旳try块输出数据不完整33OutputStreamWriter
out
=
...
java.sql.Connection
conn
=
...
try
{
Statement
stat
=
conn.createStatement();
ResultSet
rs
=
stat.executeQuery(
"select
uid,
name
from
user");
while
(rs.next())
{
out.println("ID:"
+
rs.getString("uid")
+
",姓名:
"
+
rs.getString("name"));
}
}
catch(SQLException
sqlex)
{
out.println("警告:数据不完整");
throw
new
ApplicationException(
"读取数据时出现SQL错误",
sqlex);
}
catch(IOException
ioex)
{
throw
new
ApplicationException(
"写入数据时出现IO错误",
ioex);
}
finally
{
if
(conn
!=
null)
{
try
{
conn.close();
}
catch(SQLException
sqlex2)
{
System.err(this.getClass().getName()
+
".mymethod
-
不能关闭数据库连接:
"
+
sqlex2.toString());
}
}
if
(out
!=
null)
{
try
{
out.close();
}
catch(IOException
ioex2)
{
System.err(this.getClass().getName()
+
".mymethod
-
不能关闭输出文件"
+
ioex2.toString());
}
}
}34C++Exception简介这部分使用JeanineIngber旳PPTSlides源自/~ingber/SNL/CS162/PowerPoint/Session12and13.ppt该连接似乎实效了35WhatisanException?Anyeventoutsidetheboundsofroutinebehavior.Sometypicalexamples:Errorconditions(ieiterator/offsetoutofbounds)UnexpecteddataformatMemorymanagementfailures36HandlingProblemsReturnaspecialerrorvalueT*error=“someerrorcode”;if(iter<0||iter>=maxSize)return*error;returnmat[iter];Butwhathappenshere?x=v[2]+v[4]; //notsafe!37HandlingProblemsJustDieif(iter<0||iter>=maxSize)exit(1);returnmat[iter];DieGracefullyassert(iter<0&&iter>=maxSize)returnmat[iter];Outputwhenassertfails:Assert.C:7:failedassertion`iter<0&&iter>=5'Abort38WhyUseExceptionhandling?Manytimesyoudonotknowwhatshouldbedoneifanerroroccurs.Solution:Sendnotificationandletthecallerofyourroutinetakeresponsibility.39ExceptionHandlingInC++,ExceptionHandlingallowstheprogrammertonotifytheuserwhenthereisaproblem.Theproblemcanbehandledinthenotifyingroutine,orpassedalongtothecaller.40ExceptionHandlingFacilityTheexceptionhandlingfacilityconsistsoftwoprimarycomponents:Recognizingaproblemandthrowinganexception.(try-throw)Eventualhandlingoftheexception.(catch)41Simplisticoverview:intmain(intargc,char*argv[]){stringfilename;try{if(argc<=1) throw“nocommandlinearguments”;fin.open(argv[1]);}catch(strings){cout<<“enterinputfilename“;cin>>filename;fin.open(filename.c_str());}//processdata42ThrowinganExceptionAnexceptionisthrownusingathrowstatement.Example:throw42;throw“Panicmessage”;throwIteratorOverflow(iter);IteratorOverflowe(iter);throwe;
43throwStatementAnexception(ieexpressioninathrowstatement)isanobjectofsometype.Typicallyanexceptionisaclassobjectofanexplicitlyprovidedexception
classorexception
class
hierarchy.if(iter<0||iter>=maxSize)
throwIteratorOverflow(iter,maxSize); //classconstructorreturnmat[iter];44classIteratorOverflow{public: IteratorOverflow(intindex,intmax):offset(index),bound(max){}intgetOffset(){returnoffset;}intgetBound(){returnmaxSize;}voidreset(){offset=0;}voidmessage(ostream&os=cerr){os<<“Error:offset“<<offset<<“exceedsmaximumbound“<<bound;}private:intoffset,bound;};45NothingExceptionalAboutExceptionClassesAnexceptionclasshierarchyprovides:Storagefordatathatwewishtocarryacrossfunctioncalls.Methodsfordisplayingdataandmessages.Anexceptionobjectcallsitsmessagemethodtodisplayinformationfromwithinacatchblock.46catchBlocksAprogramcatchesexceptionsbytheirtypeusingasequenceofcatchblocks.Acatchblockconsistsofthreeparts:thekeywordcatchthedeclarationofasingletypewithinparenthesesastatementblock47Example:catch(IteratorOverflow&iof){iof.message(); //messagewritestocerriof.message(log); //logisiostreamobjectiof.reset() //orsomething…}continue;Thetypeoftheexceptionobjectthatwasthrowniscomparedagainsttheexceptiondeclarationofeachcatchblockinturn.Ifthetypesmatch,thestatementblockisexecuted.Theaboverepresentsacomplete
handlingoftheexception.Normalprogramexecutioncontinueswiththefirststatementfollowingthecatchblock.48Re-throwExpressionItisoftenthecasethatwecannotcompletelyhandleanexception.Ifthisisthecase,wecanre-throwtheexception.catch(IteratorOverflow&iof){iof.message(); //messagewritestocerriof.message(log); //logisiostreamobjectthrow; }Are-throwcanoccuronlywithinacatchblockThesearchforamatchingcatchblockcontinuesupthelineIfcompletehandlinginsomecatchblockdoesnotoccur,theprogramaborts.49CatchallBlockcatch(…) //catchanyandallexceptions{cerr<<“unknowexceptionthrown.GoodBye!“;//…exit(1);}50ExceptionClassHierarchyclassMatrixException{protected:
virtualvoiddiagnostic(){cout<<"Matrixerror\n";}};classSubscriptOutOfBoundsException:publicMatrixException{protected:voiddiagnostic(intr,intc){cout<<"outofbounds"<<r<<c<<endl;}};classSizeMismatchException:publicMatrixException{protected:voiddiagnostic(){cout<<"binaryopsizemis-match\n";}};51Handlerstry{//somecodethatusesMatrixbinaryops}catch(SizeMismatchException&e){e.diagnostics();}catch(SubScriptsOutOfBounds&e){e.diagnostics();}catch(MatrixException&e){e.diagnostics();}//matchesallMatrix..52tryBlocksAtryblockbeginswiththekeywordtryfollowedbyastatementblock.Zeroormorecatchblocksfollowtheendofthetrystatementblock.Ifnoexceptionisthrownwithinthetryblock,allcatchblocksareignored.Ifanexceptionisthrownwithinthetryblock,asearchforamatchingcatchblockbegins.Ifnomatchingcatchblockisfound,searchcontinuesupthecallchain.Programabortsifamatchingcatchisnotfound.53ExceptionHandling#include<iostream>#include"Matrix.h"#include"MatrixException.h"usingnamespacestd;//functionprototypesvoidfunc();voidfuncHandlesIt();voidfuncPassItOn();voidfuncCatchAll();intmain(){funcHandlesIt();funcPassItOn();funcCatchAll();func();cout<<"LeavingMain\n";return0;}54Example:Codenotawareofproblemvoidfunc() //funcdoesn’tcare{MatrixA(4,4),B(2,2);MatrixC(4,4);C=A+B; //Exceptionthrown//Controlneverreachesthispoint//Exceptionpropagates
//Searchformatchingcatchblock.//Nonefound.Programaborts//Destructorsnotcalled.}output:Constructing0xbffffbf0Constructing0xbffffc00Constructing0xbffffc10Abort55CallerHandlesExceptionvoidfuncHandlesIt(){Matrixtemp;try{func();}catch(MatrixException&e){e.diagnostic();}cout<<“LeavingfuncHandlesIt<<endl”;}output:Constructing0xbffffc20Constructing0xbffffb80Constructing0xbffffb90Constructing0xbffffba00xbffffba0destructingmatrix0xbffffb90destructingmatrix0xbffffb80destructingmatrix
binaryopsizemis-matchLeavingfuncHandlesIt0xbffffc20destructingmatrixLeavingmainExceptiondoesnotpropagate56CallerPassesitonvoidfuncPassItOn(){Matrixtemp;try{func();}catch(MatrixException&e){cout<<"Exceptionthrown\n";throw;//ExceptionPropagates}cout<<"LeavingfuncPassItOn\n";}Constructing0xbffffc20Constructing0xbffffb80Constructing0xbffffb90Constructing0xbffffba00xbffffba0destructingmatrix0xbffffb90destructingmatrix0xbffffb80destructingmatrixExceptionthrownAbortre-thrownexceptionnothandled57CatchAllvoidfuncCatchAll(){Matrixtemp;try{func();}catch(...){cout<<"Exceptionthrown.Stopshere\n";}cout<<"LeavingfuncCatchAll\n";}output:Constructing0xbffffc20Constructing0xbffffb80Constructing0xbffffb90Constructing0xbffffba00xbffffba0destructingmatrix0xbffffb90destructingmatrix0xbffffb80destructingmatrixExceptionthrown.StopshereLeavingfuncCatchAll0xbffffc20destructingmatrixLeavingMain58Reviewthrowstatementraisestheexceptioncontrolpropagates
backtofirstcatchblockthatmatchespropagationfollowsthecallchainobjectsonstackareproperlydestroyedthrowexp;throwsobjectformatchingthrow;re-throwstheexceptionbeinghandledvalidonlywithinacatchblock59TheStandardExceptions...60bad_allocExceptionMatrix*p=0;try{p=newMatrix;}catch(bad_alloc){ //catchtype,noobjectcout<<“heapexhausted\n”;//…cleanupandexit}61bad_allocExceptionMatrix*p=0;try{p=newMatrix;}catch(bad_alloc){ //catchtype,noobjectcout<<“heapexhausted\n”;//…cleanupandexit}output:heapexausted62exceptionClassexceptionisanabstractbaseclassexceptiondeclaresavirtualfunctionnamedwhat()Classedderivedfromexceptiondefinetheirowninstanceofwhat()classMatrixException:publicexception{…}63bad_allocExceptionMatrix*p=0;try{p=newMatrix;}catch(constbad_alloc&e){e.what(); //whatreturnsaconstchar*cout<<“heapexhausted\n”;//…cleanupandexit}output:***malloc:vm_allocate(size=2211577856)failedwith3***malloc[13737]:error:Can'tallocateregionheapexausted64BenefitsofInheritingexceptionMatrixExceptionscanbecaughtwithcatch(constexception&ex){cerr<<ex.what()<<endl;}NoneedtoretrofitexistingcodetoknowaboutMatrixExceptionsclass.Noneedtouseanonymouscatch-allMustinclude<exception>65EiffelException机制简介Eiffel观点:契约破坏才会有Exception机制旳设计基于此观点66ExceptionhandlingTheneedforexceptionsariseswhenthecontractisbroken.Twoconcepts:Failure:aroutine,orotheroperation,isunabletofulfillitscontract.Exception:anundesirableeventoccursduringtheexecutionofaroutine—asaresultofthefailureofsomeoperationcalledbytheroutine.67Theoriginalstrategy
r(...)is
require ...
do
op1
op2 ...
opi ...
opn
ensure ...
endFails,triggeringanexceptioninr(risrecipientofexception).68CausesofexceptionsAssertionviolationVoidcall(x.fwithnoobjectattachedtox)Operatingsystemsignal(arithmeticoverflow,nomorememory,interrupt...)69HandlingexceptionsproperlySafeexceptionhandlingprinciple:Thereareonlytwoacceptablewaystoreactfortherecipientofanexception:Concedefailure,andtriggeranexceptioninthecaller(OrganizedPanic).Tryagain,usingadifferentstrategy(orrepeatingthesamestrategy)(Retrying).70(Fro
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2023年北京工业大学聘用制人员招聘考试真题
- 拔罐疗法治疗眼科疾病的2024年课件
- 2024年商业销售解除协议样例
- 2024年课堂教学:融入互联网教案的创新路径
- 《哭泣的自然》课件中的环保使命
- 统编版小学语文五年级下册第二单元素养练习
- 口罩订货合同范本
- 地坪工程清工承揽协议(2024年)
- 直播运费合同范本
- 安全教育讲座报告模板
- 氢气中卤化物、甲酸的测定 离子色谱法-编制说明
- 2024秋期国家开放大学专科《机械制图》一平台在线形考(形成性任务四)试题及答案
- 2024年黑龙江哈尔滨市通河县所属事业单位招聘74人(第二批)易考易错模拟试题(共500题)试卷后附参考答案
- 私募基金管理人-廉洁从业管理准则
- 房地产估价机构内部管理制度
- 广西科普传播中心招考高频难、易错点500题模拟试题附带答案详解
- 建立校园欺凌案发与处理的记录系统
- 案例一动植物细胞模型制作课件人教版生物七年级上册
- 2024下半年江苏无锡市属国企业招聘111人高频500题难、易错点模拟试题附带答案详解
- 油库设计与管理智慧树知到答案2024年中国石油大学(华东)
- 2024年安徽省地勘行业职业技能大赛(地质调查员)考试题库(含答案)
评论
0/150
提交评论