java语言程序设计基础篇课件(第13章)英文_第1页
java语言程序设计基础篇课件(第13章)英文_第2页
java语言程序设计基础篇课件(第13章)英文_第3页
java语言程序设计基础篇课件(第13章)英文_第4页
java语言程序设计基础篇课件(第13章)英文_第5页
已阅读5页,还剩45页未读 继续免费阅读

下载本文档

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

文档简介

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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论