CONFIDENTIALModule7:Exceptions第7章异常中国北京:电话:82780848/62969799地址:北京市海淀区创业中路36号留学人员创业园3062加拿大加拿大••亚思晟亚思晟((中国中国))公司公司Goals(目标)Definingexceptions异常的定义Usingtry,catch,finally,throws,throwstatements使用try,catch,finally,throws,throw语句Exceptioncategories异常的关系目录Exceptionshandling异常的处理3加拿大加拿大••亚思晟亚思晟((中国中国))公司公司BasicConceptsofExceptions异常基本概念Exceptionalconditions产生异常的条件Occurrencesthatalterthenormalprogramflow出现异常后就会改变正常的程序流程Whenanexceptionaleventoccurs,anexceptionissaidtobethrown当产生一个异常事件时,要声明抛出异常Thecodethatisresponsiblefordoingsomethingabouttheerroriscalledanexceptionhandler负责处理错误信息的代码称为异常处理器Theexceptionhandlercatchestheexception异常处理器可以捕获异常信息4加拿大加拿大••亚思晟亚思晟((中国中国))公司公司ExceptionsDeclarationandHandling异常的声明和处理Handling:try-catch-finally用try-catch-finally处理Usingthrowsstatementtodeclarethatthecodewillcauseexceptions用throws语句来声明程序代码可能会产生异常publicclassJBeesLocalFileextendsjava.lang.Object{privateRandomAccessFilelocalFile;/**CreatesnewJBeesLocalFile*/publicJBeesLocalFile(StringlocalFileName)throwsIOException{Filef=newFile(localFileName);if(f.getParent()!=null){Filedir=newFile(f.getParent());if(!dir.exists())dir.mkdirs();}localFile=newRandomAccessFile(localFileName,rw);}synchronizedpublicvoidwriteBytes(byte[]in,longoffset)throwsIOException{localFile.seek(offset);localFile.write(in);}publicvoidclose()throwsIOException{localFile.close();}}JBeesLocalFile.java5加拿大加拿大••亚思晟亚思晟((中国中国))公司公司tryandcatchstatementtrycatch语句1:try{2://Thisisthefirstlineofthe“guardedregion”3://thatisgovernedbythetrykeyword.4://Putcodeherethatmightcausesomekindofexception.5://Wemayhavemanycodelineshereorjustone.6:}7:catch(MyFirstError){8://Putcodeherethathandlesthiserror.9://Thisisthenextlineoftheexceptionhandler.10://Thisisthelastlineoftheexceptionhandler.11:}12:catch(MySecondError){13://Putcodeherethathandlesthiserror.14:}15:16://Someotherunguardedcodebeginshere6加拿大加拿大••亚思晟亚思晟((中国中国))公司公司finallystatementfinally语句1:try{2://Thisisthefirstlineofthe“guardedregion”.3:}4:catch(MyFirstError){5://Putcodeherethathandlesthiserror.6:}7:catch(MySecondError){8://Putcodeherethathandlesthiserror.9:}10:finally{11://Putcodeheretoreleaseanyresourcewe12://allocatedinthetryclause.13:}14:15://Morecodehere7加拿大加拿大••亚思晟亚思晟((中国中国))公司公司ASampleofExceptionsHandling异常处理的例子publicvoidrun(){booleanisException=false;Exceptionexc=null;Thread[]list;try{JBeesFlying();if(tg.activeCount()0){list=newThread[tg.activeCount()];intnum=tg.enumerate(list);for(inti=0;inum;i++)list[i].join();}//jblf.close();}catch(Exceptione){jbc.interrupt();exc=e;isException=true;}finally{try{jblf.close();}catch(Exceptione){}finished=true;if(!stopDownloading){if(!isException){intsegment=jbrfi.getRemoteBegin().length;intsum=0;for(inti=0;isegment;i++)sum+=(jbrfi.getRemoteEnd(i)-jbrfi.getRemoteBegin(i)+1);if(sum0){fireJBeesTeamStatusEvent();JOptionPane.showMessageDialog(null,downloadingfrom+url.toString()+failed,Error,JOptionPane.ERROR_MESSAGE);}else{success=true;fireJBeesTeamStatusEvent();if(!jbcfi.getPrompt4failure())JOptionPane.showMessageDialog(null,downloadingfrom+url.toString()+Succeeded,Success,JOptionPane.INFORMATION_MESSAGE);}}else{fireJBeesTeamStatusEvent();JOptionPane.showMessageDialog(null,exc+Exceptionsoccuredduringdownloadingfrom“+url.toString(),Exception,JOptionPane.ERROR_MESSAGE);}jbc.interrupt();fireJBeesTeamStatusEvent();}}}JBeesTeam.java8加拿大加拿大••亚思晟亚思晟((中国中国))公司公司Exceptionscallstack异常调用栈轨迹Exceptionpropagation异常的传播Anexceptionwillcauseyourapplicationtostopifitisnevercaught如果产生异常不去捕获,异常将会导致应用程序运行中断9加拿大加拿大••亚思晟亚思晟((中国中国))公司公司ExceptionCallStackSample异常调用栈轨迹的例子packagesample;publicclassExceptionStackTest{publicvoida()throwsException{b();}publicvoidb()throwsException{c();}publicvoidc()throwsException{thrownewException();}publicstaticvoidmain(String[]args){ExceptionStackTestest=newExceptionStackTest();try{est.a();}catch(Exceptione){e.printStackTrace();}finally{}}}10加拿大加拿大••亚思晟亚思晟((中国中国))公司公司ExceptionHierarchy异常的层次ClassesderivefromErrorrepresentunusualsituationsError一般由类产生的,表示类的状态不正常。Applicationswon’tbeabletorecoverfromanerror应用程序不能从error中恢复AllJava’sexceptiontypesderivefromException所有的java异常类型来自于Exception类Otherexceptions,alsocalledcheckedexceptions,mustbettd11加拿大加拿大••亚思晟亚思晟((中国中国))公司公司ExceptionHierarchy异常的层次RuntimeException,alsocalleduncheckedexception运行时异常也叫非受查异常Auncheckedexceptiondoesnothavetobecaught一个非受查异常不必必须捕获12加拿大加拿大••亚思晟亚思晟((中国中国))公司公司CommonCheckedExceptions普通受查异常java.lang.ArithmeticExceptionjava.lang.NullPointerExceptionjava.lang.ArrayIndexOutofBoundsExceptionjava.lang.SecurityExceptionJava.lang.NegativeArraySizeException13加拿大加拿大••亚思晟亚思晟((中国中国))公司公司WritingYourOwnExceptions自定义异常DerivingfromException要继承Exception类publicclassMalformedB64EncodeExceptionextendsjava.lang.Exception{/***CreatesnewcodeMalformedB64EncodeException/codewithoutdetailmessage.*/publicMalformedB64EncodeException(){this(Errorencodedstring);}/***ConstructsancodeMalformedB64EncodeException/codewiththespecifieddetailmessage.*@parammsgthedetailmessage.*/publicMalformedB