《课件Java程序设计方案教程文件》由会员分享,可在线阅读,更多相关《课件Java程序设计方案教程文件(47页珍藏版)》请在金锄头文库上搜索。
1、Java程序设计,JavaProgrammingSpring,2013,chapter8Exceptions,2,Contents,WhyExceptions?WhatareExceptions?HandlingExceptionsCreatingExceptionTypes,chapter8Exceptions,3,WhyExceptions(异常)?,Duringexecution(执行),programscanrunintomanykindsoferrors;Whatdowedowhenanerroroccurs?Javausesexceptionstoprovidetheerror-h
2、andlingcapabilitiesforitsprograms.,chapter8Exceptions,4,Exceptions(异常),ErrorClassCritical(严重的)errorwhichisnotacceptableinnormalapplicationprogram.ExceptionClassPossibleexceptioninnormalapplicationprogramexecution;Possibletohandlebyprogrammer.,chapter8Exceptions,6,Exceptions(异常),Treatexceptionasanobj
3、ect.AllexceptionsareinstancesofaclassextendedfromThrowableclassoritssubclass.Generally,aprogrammermakesnewexceptionclasstoextendtheExceptionclasswhichisasubclassofThrowableclass.,7,ExceptionClass继承关系,8,异常类的层次结构:,9,Classifying(分类)JavaExceptions,UncheckedExceptions(非检查性异常)Itisnotrequiredthatthesetypes
4、ofexceptionsbecaughtordeclaredonamethod.RuntimeexceptionscanbegeneratedbymethodsorbytheJVMitself.ErrorsaregeneratedfromdeepwithintheJVM,andoftenindicateatrulyfatalstate.CheckedExceptions(检查性异常)Musteitherbecaughtbyamethodordeclaredinitssignaturebyplacingexceptionsinthemethodsignature.,chapter8Excepti
5、ons,10,Exception的分类,非检查性异常(uncheckedexception):以RuntimeException为代表的一些类,编译时发现不了,只在能运行时才能发现。检查性异常(checkedexception):一般程序中可预知的问题,其产生的异常可能会带来意想不到的结果,因此Java编译器要求Java程序必须捕获或声明所有的非运行时异常。以IOException为代表的一些类。如果代码中存在检查性异常,必须进行异常处理,否则编译不能通过。如:用户连接数据库SQLException、FileNotFoundException。,chapter8Exceptions,11,Ex
6、ception的分类,什么是RuntimeException:Java虚拟机在运行时生成的异常,如:被0除等系统错误、数组下标超范围等,其产生比较频繁,处理麻烦,对程序可读性和运行效率影响太大。因此由系统检测,用户可不做处理,系统将它们交给默认的异常处理程序(当然,必要时,用户可对其处理)。Java程序异常处理的原则是:对于Error和RuntimeException,可以在程序中进行捕获和处理,但不是必须的。对于IOException及其他异常,必须在程序进行捕获和处理。异常处理机制主要处理检查性异常。,12,JavaExceptionTypeHierarchy(层次),virtualmac
7、hineerrors,chapter8Exceptions,13,系统异常类的层次结构:,chapter8Exceptions,14,Exception的分类,System-DefinedException(系统定义的异常)Programmer-DefinedException(程序员自定义异常),chapter8Exceptions,15,System-DefinedException(系统定义的异常),Raisedimplicitlybysystembecauseofillegalexecutionofprogram;CreatedbyJavaSystemautomatically;Exc
8、eptionextendedfromErrorclassandRuntimeExceptionclass.,16,System-DefinedException,IndexOutOfBoundsException:Whenbeyondtheboundofindexintheobjectwhichuseindex,suchasarray,string,andvectorArrayStoreException:WhenassignobjectofincorrecttypetoelementofarrayNegativeArraySizeException:Whenusinganegativesiz
9、eofarrayNullPointerException:WhenrefertoobjectasanullpointerSecurityException:Whenviolatesecurity.CausedbysecuritymanagerIllegalMonitorStateException:Whenthethreadwhichisnotownerofmonitorinvolveswaitornotifymethod,chapter8Exceptions,17,Programmer-DefinedException(程序员自定义异常),Exceptionsraisedbyprogramm
10、erSubclassofExceptionclassCheckbycompilerwhethertheexceptionhandlerforexceptionoccurredexistsornotIfthereisnohandler,itiserror.,18,User-definedExceptions(用户自定义异常),classUserErrextendsException,CreatingExceptionTypes:,chapter8Exceptions,19,Example1:,publicclassInsufficientFundsExceptionextendsExceptio
11、nprivateBankAccountexcepbank;privatedoubleexcepAmount;InsufficientFundsException(Bankba,doubledAmount)excepbank=ba;excepAmount=dAmount;,20,程序运行时发生异常,系统会抛出异常,如果程序中未处理和捕获异常,异常抛出后程序运行中断。,publicclassTestpublicintbar()inta=newint2;for(intx=0;x=2;x+)ax=0;/抛出异常,程序中断returna;publicstaticvoidmain(Stringargs)T
12、estt=newTest();t.bar();/程序中断System.out.println(“Method:foo”);/不被执行,系统给出的错误信息:Exceptioninthreadmainjava.lang.ArrayIndexOutOfBoundsException:2atexception.Test.bar(Test.java:7)atexception.Test.main(Test.java:25),chapter8Exceptions,21,HandlingExceptions(处理异常),Throwinganexception(抛出异常)Whenanerroroccurswi
13、thinamethod.Anexceptionobjectiscreatedandhandedofftotheruntimesystem(运行时系统).Theruntimesystemmustfindthecodetohandletheerror.Catchinganexception(捕获异常)Theruntimesystem(运行时系统)searchesforcodetohandlethethrownexception.Itcanbeinthesamemethodorinsomemethodinthecall(调用)stack(堆栈).,22,KeywordsforJavaExceptio
14、ns,tryMarksthestartofablockassociatedwithasetofexceptionhandlers.catchIftheblockenclosedbythetrygeneratesanexceptionofthistype,controlmoveshere;watchoutforimplicitsubsumption.finallyAlwayscalledwhenthetryblockconcludes,andafteranynecessarycatchhandleriscomplete.throwsDescribestheexceptionswhichcanbe
15、raisedbyamethod.throwRaisesanexceptiontothefirstavailablehandlerinthecallstack,unwindingthestackalongtheway.,23,抛出异常throw,throws,在一个方法的运行过程中,如果一个语句引起了错误时,含有这个语句的方法就会创建一个包含有关异常信息的异常对象,并将它传递给Java运行时系统。我们把生成异常对象并把它提交给运行时系统的过程称为抛出(throw)异常。throw在方法体中用throw手工抛出异常;throws在方法头部间接抛出异常,即:申明方法中可能抛出的异常。,24,1.在方
16、法体中用throw手工抛出异常,throw抛出异常,可以是系统定义的异常,也可以是用户自定义的异常。语法格式:或例如:下面语句就抛出了一个IOException异常:thrownewIOException();,异常类名对象名new异常类构造函数;throw对象名;,thrownew异常类构造函数;,25,throwExample,classThrowStatementextendsExceptionpublicstaticvoidexp(intptr)tryif(ptr=0)thrownewNullPointerException();catch(NullPointerExceptione)publicstaticvoidmain(Stringargs)inti=0;ThrowStatement.exp(i);,26,2.throws间接抛出异常(申明异常),一个方法不处理它产生的异常,而是沿着调用层次向上传递,由调用它的方法来处理这些异常,叫声明异常。在定义方法时用throws关键字将方法中可能产生的异常间接抛出。若一个方法可能引发一个异常,但它自己却没有