




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Java程序设计JavaProgrammingSpring,20131成都信息工程学院计算机系ContentsWhyExceptions?WhatareExceptions?HandlingExceptionsCreatingExceptionTypes2chapter8ExceptionsWhyExceptions(异常)?Duringexecution(执行),programscanrunintomanykindsoferrors;Whatdowedowhenanerroroccurs?Javausesexceptionstoprovidetheerror-handlingcapabilitiesforitsprograms.3chapter8ExceptionsExceptions(异常)ErrorClassCritical(严重的)
errorwhichisnotacceptableinnormalapplicationprogram.
ExceptionClassPossibleexceptioninnormalapplicationprogramexecution;
Possibletohandlebyprogrammer.
4chapter8ExceptionsExceptions(异常)Treatexceptionasanobject.AllexceptionsareinstancesofaclassextendedfromThrowable
classoritssubclass.
Generally,aprogrammermakesnewexceptionclasstoextendtheExceptionclasswhichisasubclassofThrowableclass.6chapter8ExceptionsExceptionClass继承关系ThrowableErrorExceptionRuntimeExceptionIOExceptionObject7异常类的层次结构:8Classifying(分类)JavaExceptionsUncheckedExceptions(非检查性异常)Itisnotrequiredthatthesetypesofexceptionsbecaughtordeclaredonamethod.RuntimeexceptionscanbegeneratedbymethodsorbytheJVMitself.Errors
aregeneratedfromdeepwithintheJVM,andoftenindicateatrulyfatalstate.CheckedExceptions(检查性异常)Musteitherbecaughtbyamethodordeclaredinitssignaturebyplacingexceptionsinthemethodsignature.9Exception的分类非检查性异常(uncheckedexception):以RuntimeException为代表的一些类,编译时发现不了,只在能运行时才能发现。检查性异常(checkedexception):一般程序中可预知的问题,其产生的异常可能会带来意想不到的结果,因此Java编译器要求Java程序必须捕获或声明所有的非运行时异常。以IOException为代表的一些类。如果代码中存在检查性异常,必须进行异常处理,否则编译不能通过。如:用户连接数据库SQLException、FileNotFoundException。10chapter8ExceptionsException的分类什么是RuntimeException:Java虚拟机在运行时生成的异常,如:被0除等系统错误、数组下标超范围等,其产生比较频繁,处理麻烦,对程序可读性和运行效率影响太大。因此由系统检测,用户可不做处理,系统将它们交给默认的异常处理程序(当然,必要时,用户可对其处理)。Java程序异常处理的原则是:对于Error和RuntimeException,可以在程序中进行捕获和处理,但不是必须的。对于IOException及其他异常,必须在程序进行捕获和处理。异常处理机制主要处理检查性异常。11chapter8ExceptionsJavaExceptionTypeHierarchy(层次)virtualmachineerrors12系统异常类的层次结构:13chapter8ExceptionsException的分类System-DefinedException(系统定义的异常)Programmer-DefinedException(程序员自定义异常)14chapter8ExceptionsSystem-DefinedException
(系统定义的异常)Raisedimplicitlybysystembecauseofillegalexecutionofprogram;CreatedbyJavaSystemautomatically;ExceptionextendedfromErrorclassandRuntimeExceptionclass.
15chapter8ExceptionsSystem-DefinedExceptionIndexOutOfBoundsException:Whenbeyondtheboundofindexintheobjectwhichuseindex,suchasarray,string,andvectorArrayStoreException:WhenassignobjectofincorrecttypetoelementofarrayNegativeArraySizeException:
WhenusinganegativesizeofarrayNullPointerException:WhenrefertoobjectasanullpointerSecurityException:Whenviolatesecurity.CausedbysecuritymanagerIllegalMonitorStateException:Whenthethreadwhichisnotownerofmonitorinvolveswaitornotifymethod16Programmer-DefinedException
(程序员自定义异常)
Exceptionsraisedbyprogrammer
SubclassofException
classCheckbycompilerwhethertheexceptionhandlerforexceptionoccurredexistsornotIfthereisnohandler,itiserror.
17chapter8ExceptionsUser-definedExceptions
(用户自定义异常)classUserErrextendsException
{ …}CreatingExceptionTypes:18Example1:publicclassInsufficientFundsException
extendsException
{ privateBankAccountexcepbank;privatedoubleexcepAmount;
InsufficientFundsException(Bankba,doubledAmount) { excepbank=ba;excepAmount=dAmount; }}19chapter8Exceptions程序运行时发生异常,系统会抛出异常,如果程序中未处理和捕获异常,异常抛出后程序运行中断。publicclassTest{publicint[]bar(){ inta[]=newint[2]; for(intx=0;x<=2;x++){
a[x]=0;//抛出异常,程序中断} returna;}publicstaticvoidmain(String[]args){ Testt=newTest(); t.bar(); //程序中断 System.out.println(“Method:foo”);//不被执行}}系统给出的错误信息:Exceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException:2atexception.Test.bar(Test.java:7)atexception.Test.main(Test.java:25)20HandlingExceptions(处理异常)Throwinganexception(抛出异常)Whenanerroroccurswithinamethod.Anexceptionobjectiscreatedandhandedofftotheruntimesystem(运行时系统).Theruntimesystemmustfindthecodetohandletheerror.Catchinganexception(捕获异常)Theruntimesystem(运行时系统)searchesforcodetohandlethethrownexception.Itcanbeinthesamemethodorinsomemethodinthecall(调用)stack(堆栈).21chapter8ExceptionsKeywordsforJavaExceptionstry
Marksthestartofablockassociatedwithasetofexceptionhandlers.catch
Iftheblockenclosedbythetrygeneratesanexceptionofthistype,controlmoveshere;watchoutforimplicitsubsumption.finally
Alwayscalledwhenthetryblockconcludes,andafteranynecessarycatchhandleriscomplete.throws
Describestheexceptionswhichcanberaisedbyamethod.throw
Raisesanexceptiontothefirstavailablehandlerinthecallstack,unwindingthestackalongtheway.22抛出异常–throw,throws在一个方法的运行过程中,如果一个语句引起了错误时,含有这个语句的方法就会创建一个包含有关异常信息的异常对象,并将它传递给Java运行时系统。我们把生成异常对象并把它提交给运行时系统的过程称为抛出(throw)异常。throw
—在方法体中用throw手工抛出异常;throws—在方法头部间接抛出异常,即:申明方法中可能抛出的异常。231.在方法体中用throw手工抛出异常throw抛出异常,可以是系统定义的异常,也可以是用户自定义的异常。语法格式:或例如:下面语句就抛出了一个IOException异常:thrownewIOException();异常类名对象名=new异常类构造函数;throw对象名;thrownew异常类构造函数;24throw
-ExampleclassThrowStatementextendsException{publicstaticvoidexp(intptr){ try{ if(ptr==0)
thrownewNullPointerException();
} catch(NullPointerExceptione){}}
publicstaticvoidmain(String[]args){inti=0;
ThrowStatement.exp(i);}}252.throws—间接抛出异常(申明异常)一个方法不处理它产生的异常,而是沿着调用层次向上传递,由调用它的方法来处理这些异常,叫声明异常。在定义方法时用throws关键字将方法中可能产生的异常间接抛出。若一个方法可能引发一个异常,但它自己却没有处理,则应该声明异常,并让其调用者来处理这个异常,这时就需要用throws关键字来指明方法中可能引发的所有异常。类型方法名(参数列表)throws
异常列表{ //…代码}26Example1:publicclassExceptionTest{ voidProc(intsel)throwsArrayIndexOutOfBoundsException{
System.out.println(“InSituation"+sel); if(sel==1){ intiArray[]=newint[4];iArray[10]=3;//抛出异常 }
}
}27异常向上传递-ExampleclassThrowStatementextendsException{publicstaticvoidexp(intptr)throws
NullPointerException{if(ptr==0)
thrownewNullPointerException();}
publicstaticvoidmain(String[]args){inti=0;
ThrowStatement.exp(i);}}运行结果:
java.lang.NullPointerExceptionatThrowStatement.exp(ThrowStatement.java:4)atThrowStatement.main(ThrowStatement.java:8)28Exceptions-throwingmultiple(多个)
exceptionsAMethodcanthrowmultipleexceptions.Multipleexceptionsareseparatedbycommasafterthethrowskeyword:publicclassMyClass{ publicintcomputeFileSize()
throwsIOException,ArithmeticException { ...}}29HandlingExceptions在一个方法中,对于可能抛出的异常,处理方式有两种:一个方法不处理它产生的异常,只在方法头部声明使用throws抛出异常,使异常沿着调用层次向上传递,由调用它的方法来处理这些异常。用try-catch-finally语句对异常及时处理;30HandlingExceptionspublicvoidreplaceValue(Stringname,Objectvalue)
throwsNoSuchAttributeException{Attrattr=find(name);if(attr==null)
thrownewNoSuchAttributeException(name);
attr.setValue(value);}try{…
replaceValue(“att1”,“newValue”);…}catch(NoSuchAttributeExceptione){e.printStackTrace();}当replaceValue(…)方法被调用时,调用者需处理异常。31处理异常语句try-catch-finally的基本格式为:try{ //可能产生异常的代码;}//不能有其它语句分隔catch(异常类名异常对象名){ //异常处理代码;//要处理的第一种异常}catch(异常类名异常对象名){ //异常处理代码;//要处理的第二种异常}…finally{ //最终处理(缺省处理)}32Exceptions–Syntax(语法)示例try{
//Codewhichmightthrowanexception //...}catch(FileNotFoundExceptionx){
//codetohandleaFileNotFoundexception}catch(IOExceptionx){
//codetohandleanyotherI/Oexceptions}catch(Exceptionx){
//Codetocatchanyothertypeofexception}finally{
//ThiscodeisALWAYSexecutedwhetheranexceptionwasthrown //ornot.Agoodplacetoputclean-upcode.ie.close //anyopenfiles,etc...}33HandlingExceptions(处理异常)try-catch或try-catch-finally.Threestatementshelpdefinehowexceptionsarehandled:tryidentifiesablockofstatementswithinwhichanexceptionmightbethrown;Atrystatementcanhavemultiplecatchstatementsassociatedwithit.catchmustbeassociatedwithatrystatementandidentifiesablockofstatementsthatcanhandleaparticulartypeofexception.Thestatementsareexecutedifanexceptionofaparticulartypeoccurswithinthetryblock.34HandlingExceptionsfinally(可选项)mustbeassociatedwithatrystatementandidentifiesablockofstatementsthatareexecutedregardlessofwhetherornotanerroroccurswithinthetryblock.Evenifthetryandcatchblockhaveareturnstatementinthem,finallywillstillrun.35用try-catch-finally语句对异常及时处理-ExampleclassThrowStatementextendsException{publicstaticvoidexp(intptr){ try{ if(ptr==0)
thrownewNullPointerException(); } catch(NullPointerExceptione){}}
publicstaticvoidmain(String[]args){inti=0;
ThrowStatement.exp(i);}}36系统抛出异常后,捕获异常,运行finally块,程序运行继续。publicclassTest{ publicvoidfoo(){
try{ inta[]=newint[2];
a[4]=1;/*causesaruntimeexceptionduetotheindex*/System.out.println(“Method:foo”);//若异常发生,不执行}catch(ArrayIndexOutOfBoundsExceptione){System.out.println("exception:"+e.getMessage()); e.printStackTrace();}finally{System.out.println("Finallyblockalwaysexecute!!!");}}publicstaticvoidmain(String[]args){Testt=newTest();t.foo();
System.out.println(“ExcecutionafterException!!!”);
//继续执行}}37运行结果:exception:4java.lang.ArrayIndexOutOfBoundsException:4 atexception.Test.foo(Test.java:8) atexception.Test.main(Test.java:20)Finallyblockalwaysexecute!!!ExcecutionafterException!!!38Exceptions-throwingmultipleexceptionspublicvoidmethod1(){ MyClassanObject=newMyClass(); try{ inttheSize=anOputeFileSize(); }catch(ArithmeticExceptionx){ //... }catch(IOExceptionx){ //...}}39Exceptions-catchingmultipleexceptionsEachtryblockcancatchmultipleexceptions.StartwiththemostspecificexceptionsFileNotFoundExceptionisasubclassofIOExceptionItMUSTappearbeforeIOException
inthecatchlistpublicvoidmethod1(){ FileInputStreamaFile; try{ aFile=newFileInputStream(...); intaChar=aFile.read(); //... }catch(FileNotFoundExceptionx){ //... }catch(IOExceptionx){ //...}}40Exception-Thecatch-allHandlerSinceallExceptionclassesareasubclassoftheExceptionclass,acatchhandlerwhichcatches"Exception"willcatchallexceptions.ItmustbethelastinthecatchList.publicvoidmethod1(){ FileInputStreamaFile; try{ aFile=newFileInputStream(...); intaChar=aFile.read(); //... } catch(IOExceptionx){ //... } catch(Exceptionx){ //CatchAllExceptions}}41User-definedExceptions(用户自定义异常)的处理classUserErrextendsException{ …}用户自定义异常是检查性异常(checkedexception),必须用throw手工抛出并处理。classUserClass{ …
UserErr
x=newUserErr();...if(val<1)
throw
x;}42//ThrowExample.javaclassIllegalValueException extendsException{}
classUserTrial{intval1,val2;publicUserTrial(inta,intb){val1=a;val2=b;}voidshow()throwsIllegalValueException{
if((val1<0)||(val2>0)) thrownewIllegalValueException();System.out.println(“Value1=”+val1);//不运行System.out.println("Value2="+val2);}}classThrowExample{publicstaticvoidmain(Stringargs[]){
UserTrialvalues=newUserTrial(-1,1);try{ values.show();}catch(IllegalValueExceptione){Syst
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 《一个中国孩子的呼声》课件-1
- 《依法参与政治生活》参与政治生活课件-1
- 2025企业终止合同相关法规
- 2025年广州市外地员工劳动合同范本
- 2025版农产品订购合同(参考文本)
- 防跌倒护理小讲课教案
- 2025林地买卖合同书模板
- 2025智能家居设备经销合同
- 代练接单合同范本
- 课程的结课汇报
- 2023年北京按摩医院招聘笔试真题
- 2024年山东省烟台市初中学业水平考试地理试卷含答案
- 中国生殖支原体感染诊疗专家共识(2024年版)解读课件
- 人教版小学三年级下期数学单元、期中和期末检测试题
- 森林经理学 课程设计
- 工会驿站验收
- “双减”政策(2023年陕西中考语文试卷非连续性文本阅读题及答案)
- 【全友家居企业绩效考核问题及其建议(论文8500字)】
- 职业技术学校《云计算运维与开发(初级)》课程标准
- 幼儿园大班数学练习题直接打印
- 100以内整十数加减法100道口算题(19套)
评论
0/150
提交评论