版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter13ExceptionHandling1MotivationsWhenaprogramrunsintoaruntimeerror,theprogramterminatesabnormally.Howcanyouhandletheruntimeerrorsothattheprogramcancontinuetorunorterminategracefully?Thisisthesubjectwewillintroduceinthischapter.2
ObjectivesTogetanoverviewofexceptionsandexceptionhandling(§13.2).Toexploretheadvantagesofusingexceptionhandling(§13.3).Todistinguishexceptiontypes:Error(fatal)vs.Exception(nonfatal),andcheckedvs.unchecked(§13.4).Todeclareexceptionsinamethodheader(§13.5.1).Tothrowexceptionsinamethod(§13.5.2).Towriteatry-catchblocktohandleexceptions(§13.5.3).Toexplainhowanexceptionispropagated(§13.5.3).Tousethefinallyclauseinatry-catchblock(§13.6).Touseexceptionsonlyforunexpectederrors(§13.7).Torethrowexceptionsinacatchblock(§13.8).Tocreatechainedexceptions(§13.9).Todefinecustomexceptionclasses(§13.10).3Exception-HandlingOverview4QuotientRunQuotientWithIfRunQuotientWithExceptionRunShowruntimeerrorFixitusinganifstatementWhatiftheruntimeerroroccursinacalledmethod?ExceptionAdvantages5QuotientWithMethodRunNowyouseetheadvantagesofusingexceptionhandling.Itenablesamethodtothrowanexceptiontoitscaller.Withoutthiscapability,amethodmusthandletheexceptionorterminatetheprogram.HandlingInputMismatchException6InputMismatchExceptionDemoRunByhandlingInputMismatchException,yourprogramwillcontinuouslyreadaninputuntilitiscorrect.ExceptionTypes7SystemErrors8SystemerrorsarethrownbyJVMandrepresentedintheErrorclass.TheErrorclassdescribesinternalsystemerrors.Sucherrorsrarelyoccur.Ifonedoes,thereislittleyoucandobeyondnotifyingtheuserandtryingtoterminatetheprogramgracefully.
Exceptions9Exceptiondescribeserrorscausedbyyourprogramandexternalcircumstances.Theseerrorscanbecaughtandhandledbyyourprogram.RuntimeExceptions10RuntimeExceptioniscausedbyprogrammingerrors,suchasbadcasting,accessinganout-of-boundsarray,andnumericerrors.CheckedExceptionsvs.UncheckedExceptions11RuntimeException,Errorandtheirsubclassesareknownasunchecked
exceptions.Allotherexceptionsareknownascheckedexceptions,meaningthatthecompilerforcestheprogrammertocheckanddealwiththeexceptions.
UncheckedExceptions12Inmostcases,uncheckedexceptionsreflectprogramminglogicerrorsthatarenotrecoverable.Forexample,aNullPointerExceptionisthrownifyouaccessanobjectthroughareferencevariablebeforeanobjectisassignedtoit;anIndexOutOfBoundsExceptionisthrownifyouaccessanelementinanarrayoutsidetheboundsofthearray.Thesearethelogicerrorsthatshouldbecorrectedintheprogram.Uncheckedexceptionscanoccuranywhereintheprogram.Toavoidcumbersomeoveruseoftry-catchblocks,Javadoesnotmandateyoutowritecodetocatchuncheckedexceptions.UncheckedExceptions13Uncheckedexception.Declaring,Throwing,andCatchingExceptions14DeclaringExceptionsEverymethodmuststatethetypesofcheckedexceptionsitmightthrow.Thisisknownasdeclaringexceptions.publicvoidmyMethod()throwsIOExceptionpublicvoidmyMethod()throwsIOException,OtherException15ThrowingExceptionsWhentheprogramdetectsanerror,theprogramcancreateaninstanceofanappropriateexceptiontypeandthrowit.Thisisknownasthrowinganexception.Hereisanexample,thrownewTheException();TheExceptionex=newTheException();
throwex;16ThrowingExceptionsExample
/**Setanewradius*/publicvoidsetRadius(doublenewRadius)
throwsIllegalArgumentException{if(newRadius>=0)radius=newRadius;else
thrownewIllegalArgumentException("Radiuscannotbenegative");}17CatchingExceptionstry{statements;//Statementsthatmaythrowexceptions}catch(Exception1exVar1){handlerforexception1;}catch(Exception2exVar2){handlerforexception2;}...catch(ExceptionNexVar3){handlerforexceptionN;}
18CatchingExceptions19CatchorDeclareCheckedExceptionsJavaforcesyoutodealwithcheckedexceptions.Ifamethoddeclaresacheckedexception(i.e.,anexceptionotherthanErrororRuntimeException),youmustinvokeitinatry-catchblockordeclaretothrowtheexceptioninthecallingmethod.Forexample,supposethatmethodp1invokesmethodp2andp2maythrowacheckedexception(e.g.,IOException),youhavetowritethecodeasshownin(a)or(b).20Example:Declaring,Throwing,andCatchingExceptionsObjective:Thisexampledemonstratesdeclaring,throwing,andcatchingexceptionsbymodifyingthesetRadiusmethodintheCircleclassdefinedinChapter8.ThenewsetRadiusmethodthrowsanexceptionifradiusisnegative.21TestCircleWithExceptionRunCircleWithExceptionRethrowingExceptionstry{statements;}catch(TheExceptionex){performoperationsbeforeexits;throwex;}22ThefinallyClausetry{statements;}catch(TheExceptionex){handlingex;}finally{finalStatements;}23TraceaProgramExecutiontry{statements;}catch(TheExceptionex){handlingex;}finally{finalStatements;}Nextstatement;24animationSupposenoexceptionsinthestatementsTraceaProgramExecutiontry{statements;}catch(TheExceptionex){handlingex;}finally{finalStatements;}Nextstatement;25animationThefinalblockisalwaysexecutedTraceaProgramExecutiontry{statements;}catch(TheExceptionex){handlingex;}finally{finalStatements;}Nextstatement;26animationNextstatementinthemethodisexecutedTraceaProgramExecutiontry{statement1;statement2;statement3;}catch(Exception1ex){handlingex;}finally{finalStatements;}Nextstatement;27animationSupposeanexceptionoftypeException1isthrowninstatement2TraceaProgramExecutiontry{statement1;statement2;statement3;}catch(Exception1ex){handlingex;}finally{finalStatements;}Nextstatement;28animationTheexceptionishandled.TraceaProgramExecutiontry{statement1;statement2;statement3;}catch(Exception1ex){handlingex;}finally{finalStatements;}Nextstatement;29animationThefinalblockisalwaysexecuted.TraceaProgramExecutiontry{statement1;statement2;statement3;}catch(Exception1ex){handlingex;}finally{finalStatements;}Nextstatement;30animationThenextstatementinthemethodisnowexecuted.TraceaProgramExecutiontry{statement1;statement2;statement3;}catch(Exception1ex){handlingex;}catch(Exception2ex){handlingex;throwex;}finally{finalStatements;}Nextstatement;31animationstatement2throwsanexceptionoftypeException2.TraceaProgramExecutiontry{statement1;statement2;statement3;}catch(Exception1ex){handlingex;}catch(Exception2ex){handlingex;throwex;}finally{finalStatements;}Nextstatement;32animationHandlingexceptionTraceaProgramExecutiontry{statement1;statement2;statement3;}catch(Exception1ex){handlingex;}catch(Exception2ex){handlingex;throwex;}finally{finalStatements;}Nextstatement;33animationExecutethefinalblockTraceaProgramExecutiontry{statement1;statement2;statement3;}catch(Exception1ex){handlingex;}catch(Exception2ex){handlingex;throwex;}finally{finalStatements;}Nextstatement;34animationRethrowtheexceptionandcontrolistransferredtothecallerCautionsWhenUsingExceptionsExceptionhandlingseparateserror-handlingcodefromnormalprogrammingtasks,thusmakingprogramseasiertoreadandtomodify.Beaware,however,thatexceptionhandlingusuallyrequiresmoretimeandresourcesbecauseitrequiresinstantiatinganewexceptionobject,rollingbackthecallstack,andpropagatingtheerrorstothecallingmethods.35WhentoThrowExceptionsAnexceptionoccursinamethod.Ifyouwanttheexceptiontobeprocessedbyitscaller,youshouldcreateanexceptionobjectandthrowit.Ifyoucanhandletheexceptioninthemethodwhereitoccurs,thereisnoneedtothrowit.36WhentoUseExceptionsWhenshouldyouusethetry-catchblockinthecode?Youshoulduseittodealwithunexpectederrorconditions.Donotuseittodealwithsimple,expectedsituations.Forexample,thefollowingcode37try{System.out.println(refVar.toString());}catch(NullPointerExceptionex){System.out.println("refVarisnull");}WhentoUseExceptionsisbettertobereplacedby38if(refVar!=null)System.out.println(refVar.toString());elseSystem.out.println("refVarisnull");DefiningCustomExceptionClasses39UsetheexceptionclassesintheAPIwheneverpossible.Definecustomexceptionclassesifthepredefinedclassesarenotsufficient.DefinecustomexceptionclassesbyextendingExceptionorasubclassofException.CustomExceptionClassExample40RunInvalidRadiusExceptionInListing13.8,thesetRadiusmethodthrowsanexceptioniftheradiusisnegative.Supposeyouwishtopasstheradiustothehandler,youhavetocreateacustomexceptionclass.CircleWithRadiusExceptionTestCircleWithRadiusExceptionAssertionsAnassertionisaJavastatementthatenablesyoutoassertanassumptionaboutyourprogram.AnassertioncontainsaBooleanexpressionthatshouldbetrueduringprogramexecution.Assertionscanbeusedtoassureprogramcorrectnessandavoidlogicerrors.
41CompanionWebsiteDeclaringAssertionsAnassertionisdeclaredusingthenewJavakeywordassertinJDK1.4asfollows:assertassertion;orassertassertion:detailMessage;whereassertionisaBooleanexpressionanddetailMessageisaprimitive-typeoranObjectvalue.42CompanionWebsiteExecutingAssertionsWhenanassertionstatementisexecuted,Javaevaluatestheassertion.Ifitisfalse,anAssertionErrorwillbethrown.TheAssertionErrorclasshasano-argconstructorandsevenoverloadedsingle-argumentconstructorsoftypeint,long,float,double,boolean,char,andObject.Forthefirstassertstatementwithnodetailmessage,theno-argconstructorofAssertionErrorisused.Forthesecondassertstatementwithadetailmessage,anappropriateAssertionErrorconstructorisusedtomatchthedatatypeofthemessage.SinceAssertionErrorisasubclassofError,whenanassertionbecomesfalse,theprogramdisplaysamessageontheconsoleandexits.43CompanionWebsiteExecutingAssertionsExamplepublicclassAssertionDemo{publicstaticvoidmain(String[]args){inti;intsum=0;for(i=0;i<10;i++){sum+=i;}asserti==10;assertsum>10&&sum<5*10:"sumis"+sum;}}44CompanionWebsiteCompilingProgramswithAssertionsSinceassertisanewJavakeywordintroducedinJDK1.4,youhavetocompiletheprogramusingaJDK1.4compiler.Furthermore,youneedtoincludetheswitch–source1.4inthecompilercommandasfollows:javac–source1.4AssertionDemo.javaNOTE:IfyouuseJDK1.5,thereisnoneedtousethe–source1.4optioninthecommand.45CompanionWebsiteRunningProgramswithAssertionsBydefault,theassertionsaredisabledatruntime.Toenableit,usetheswitch–enableassertions,or–eaforshort,asfollows:java–eaAssertionDemoAssertionscanbeselectivelyenabledordisabledatclasslevelorpackagelevel.Thedisableswitchis–disableassertionsor–daforshort.Forexample,thefollowingcommandenablesassertionsinpackagepackage1anddisablesassertionsinclassClass1.java–ea:package1–da:Class1AssertionDemo46CompanionWebsiteUsingExceptionHandlingorAssertionsAssertionshouldnotbeusedtoreplaceexceptionhandling.Exceptionhandlingdealswithunusualcircumstancesduringprogramexecution.Assertionsaretoassurethecorrectnessoftheprogram.Exceptionhandlingaddressesrobustnessand
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 二零二五年度设施农业种植与销售合同3篇
- 2025农村自建房绿色建材采购与应用合同
- 二零二五年度兼职业务员客户满意度调查合同3篇
- 2025年度公司解除与因自然灾害影响员工劳动合同证明3篇
- 二零二五年度环保材料研发与应用股东合伙人协议3篇
- 2025技术培训合同范本
- 2025年度创意产业园区商铺租赁管理协议3篇
- 2025年度矿山矿产资源勘查与开发利用合作协议3篇
- 二零二五年度地质勘探驾驶员聘用合同协议书3篇
- 二零二五年度市政工程机械租赁与施工合同3篇
- 后勤外包服务保密管理制度范文
- 小学国庆节主题活动方案设计(四篇)
- 行政事业单位内部控制培训课件
- 2009别克昂科雷维修手册gd扉页
- 数字化转型对企业创新能力的影响研究
- 替人追款协议书
- 六西格玛(6Sigma)详解及实际案例分析
- 周期性麻痹-课件
- 《推进家政服务提质扩容:家政服务业发展典型案例汇编》读书笔记模板
- XX半导体公司厂务工程项目管理制度规定
- 检测与转换技术课后习题和例题解答
评论
0/150
提交评论