Java程序设计英文版课件:ch12 Error Handling with Exceptions

上传人:枫** 文档编号:568783505 上传时间:2024-07-26 格式:PPT 页数:34 大小:792KB
返回 下载 相关 举报
Java程序设计英文版课件:ch12 Error Handling with Exceptions_第1页
第1页 / 共34页
Java程序设计英文版课件:ch12 Error Handling with Exceptions_第2页
第2页 / 共34页
Java程序设计英文版课件:ch12 Error Handling with Exceptions_第3页
第3页 / 共34页
Java程序设计英文版课件:ch12 Error Handling with Exceptions_第4页
第4页 / 共34页
Java程序设计英文版课件:ch12 Error Handling with Exceptions_第5页
第5页 / 共34页
点击查看更多>>
资源描述

《Java程序设计英文版课件:ch12 Error Handling with Exceptions》由会员分享,可在线阅读,更多相关《Java程序设计英文版课件:ch12 Error Handling with Exceptions(34页珍藏版)》请在金锄头文库上搜索。

1、1 1Chapter 12Error Handling with Exceptions2Why?人非圣贤,孰能无过。人非圣贤,孰能无过。过而能改,善莫大焉。过而能改,善莫大焉。3Basic exceptionsvErrorsalwaysoccurinsoftwareprograms.Whatreallymattersis:Howistheerrorhandled?Whohandlesit?Cantheprogramrecover,orjustprinterrormessagesandexit?InCandotherearlierlanguages,youreturnedaspecialvalu

2、eorsetaflag,andtherecipientwassupposedtolookatthevalueortheflagtodetermineifsomethingwaswrong.TheJavaprogramminglanguageusesexceptionsforerrorhandling.Errorcompile-time Errorrun-time Error4int readFile initialize errorCode = 0; open the file; if (theFileIsOpen) determine the length of the file; if (

3、gotTheFileLength) allocate that much memory; if (gotEnoughMemory) read the file into memory; if (readFailed) errorCode = -1; else errorCode = -2; else errorCode = -3; close the file; if (theFileDidntClose & errorCode = 0) errorCode = -4; else errorCode = errorCode and -4; else errorCode = -5; return

4、 errorCode;5void readFile() try open the file; determine its size; allocate that much memory; read the file into memory; close the file; catch (fileOpenFailed) doSomething; catch (sizeDeterminationFailed) doSomething; catch (memoryAllocationFailed) doSomething; catch (readFailed) doSomething; catch

5、(fileCloseFailed) doSomething; /Processing flow is straight forward. /Error will not be neglected.6Error Handling with ExceptionsvBasic exceptionsvThrow an exceptionvCatching an exceptionvCreating your own exceptionsvThe exception specificationvStandard Java exceptionsvThe special case of RuntimeExc

6、eptionvPerforming cleanup with finallyvException restrictionsvException matchingvExercises7Whats an Exception vThetermexceptionisshorthandforthephraseexceptionalevent.Definition:Anexceptionisaneventthatoccursduringtheexecutionofaprogramthatdisruptsthenormalflowofinstructions.Classification:Exception

7、andErrorvHowtodistinguishanexceptionalconditionfromanormalproblem:Normalproblem:whenyouhaveenoughinformationinthecurrentcontexttosomehowcopewiththedifficulty.Exceptionalcondition:youcannotcontinueprocessingbecauseyoudonthavetheinformationnecessarytodealwiththeproblemin the current context.Allyoucand

8、oisjumpoutofthecurrentcontextandrelegatethatproblemtoahighercontext.Thisiswhathappenswhenyouthrowanexception.vAsimpleexampleisadivide.Ifyoureabouttodividebyzero,itsworthcheckingtomakesureyoudontgoaheadandperformthedivide.Butwhatdoesitmeanthatthedenominatoriszero?8Throwable RuntimeException,IOExcepti

9、on,ArithmeticException,FileNotFoundException,OutOfMemoryException,ArrayIndexOutofBoundsException,NullPointerExceptionAbstractMethodError,IllegalAccessError,InternalError,NoClassDefFoundError,NoSuchMethodError,OutOfMemoryError,AWTError,UnknownErrorExceptionErrorObject Whats an Exception 9Throw an Exc

10、eptionvTherearetwoconstructorsinallstandardexceptions:thefirstisthedefaultconstructor,andthesecondtakesastringargumentsoyoucanplacepertinentinformationintheexception:if(t = null) throwthrow new NullPointerException(); if(t = null) throwthrow new NullPointerException(t = null); 10class TooBig extends

11、 Exception class TooSmall extends Exception class DivZero extends Exception public class MyDivide double div(double a, double b) throws TooBig, TooSmall, DivZero double ret;if ( b=0.0) throw new DivZero();ret = a/b;if(ret 1000) throw new TooBig (); return ret; /: 11Catching an exceptionvWhendoesanex

12、ceptionoccur?WhenyouthrowanexceptionOranothermethodyoucallthrowsanexceptionvIfyoureinsideamethodandanexceptionoccurs,thatmethodwillexitintheprocessofthrowing.vIfyoudontwanttoexitthemethod,youcansetupaspecialblocktocapturetheexception.Thisiscalledthetryblock.12Catching an exceptiontry / Code that mig

13、ht generate exceptions catch(Type1 id1) / Handle exceptions of Type1 catch(Type2 id2) / Handle exceptions of Type2 catch(Type3 id3) / Handle exceptions of Type3 / etc.vThehandlersmustappeardirectlyafterthetryblock.vIfanexceptionisthrown,theexceptionhandlingmechanismgoeshuntingforthefirsthandlerthatm

14、atchesthetypeoftheexception.Thenitentersthatcatchclause,andtheexceptionisconsideredhandled.Thesearchforhandlersstopsoncethecatchclauseisfinished.13public class Equalsmethod public static void main(String args) double d=new double10; System.out.println(d10); Double D=new Double10; System.out.println(

15、Program continue. ); C:Javajdk1.5.0binjava EqualsmethodException in thread main java.lang.ArrayIndexOutOfBoundsException: 10 at Equalsmethod.main(Equalsmethod.java:8)14public class Equalsmethod public static void main(String args) double d=new double10; try System.out.println(d10); catch(Exception e

16、) System.out.println(I caught it!); Double D=new Double10; System.out.println(Program continue. ); C:Javajdk1.5.0binjava EqualsmethodI caught it!Program continue.15vTo create your own exception class, you must inherit from an existing exception class.vpreferably one that is close in meaning to your

17、new exception.vThe most trivial way to create a new type of exception is just to let the compiler create the default constructor for you.Creating your own exceptions 16class SimpleException extends Exception public class SimpleExceptionDemo public void f() throws SimpleException System.out.println(

18、Throwing SimpleException from f(); throw new SimpleException (); public static void main(String args) SimpleExceptionDemo sed = new SimpleExceptionDemo(); try sed.f(); catch(SimpleException e) System.err.println(Caught it!); /: Throw SimpleException from f()Caught it!Creating your own exceptions 17T

19、he exception specificationvInJava,yourerequiredtoinformtheclientprogrammer,whocallsyourmethod,oftheexceptionsthatmightbethrownfromyourmethod.vTheexceptionspecificationusesanadditionalkeyword,throws,followedbyalistofallthepotentialexceptiontypes.void f() throwsthrows TooBig, TooSmall, DivZero /. Ifyo

20、usayvoid f() / . vitmeansthatnoexceptionsarethrownfromthemethod.(Except fortheexceptionsoftypeRuntimeException,whichcanreasonablybethrownanywherethiswillbedescribedlater.)18Catching any exceptionvBycatchingthebase-classexceptiontypeException,itispossibletocreateahandlerthatcatchesanytypeofexception.

21、catch(Exception e) System.err.println(Caught an exception); vThiswillcatchanyexception,youshouldputitattheendofyourlistofhandlerstoavoidpreemptinganyexceptionhandlersthatmightotherwisefollowit.19Methods of ExceptionvMethods of Exception (In fact come from its base type Throwable )String getMessage(

22、) -detail messageString getLocalizedMessage( ) -detail messageString toString( ) - short description + detail messagevoid printStackTrace( ) void printStackTrace(PrintStream)void printStackTrace(PrintWriter) 2021public class ExceptionMethods public static void main(String args) try throw new Excepti

23、on(Heres my Exception); catch(Exception e) System.err.println(Caught Exception); System.err.println( e.getMessage(): + e.getMessage(); System.err.println( e.getLocalizedMessage(): + e.getLocalizedMessage(); System.err.println(e.toString(): + e); System.err.println(e.printStackTrace():); e.printStack

24、Trace(System.err); /: Caught Exceptione.getMessage(): Heres my Exceptione.getLocalizedMessage(): Heres my Exceptione.toString(): java.lang.Exception: Heres my Exceptione.printStackTrace():java.lang.Exception: Heres my Exception at ExceptionMethods.main(ExceptionMethods.java:7)22Standard Java excepti

25、onsvTheJavaclassThrowabledescribesanythingthatcanbethrownasanexception.23The special case of RuntimeException)JavawillautomaticallythrowaNullPointerException.if(t = null) throw new NullPointerException();else t.somefunc();theabovebitofcodeequalsto: t.somefunc();24The special case of RuntimeException

26、)YouneverneedtowriteanexceptionspecificationsayingthatamethodmightthrowaRuntimeException,sincethatsjustassumed.Becausetheyindicatebugs,youvirtuallynevercatchaRuntimeException )Sincethecompilerdoesntenforceexceptionspecificationsforthese,itsquiteplausiblethataRuntimeExceptioncouldpercolateallthewayou

27、ttoyourmain() methodwithoutbeingcaught. ArithmeticException, ClassCastException, llegalArgumentException, IllegalStateException, IndexOutOfBoundsException, NoSuchElementException, NullPointerException, 25The special case of RuntimeExceptionpublic class NeverCaught static void f() throw new RuntimeEx

28、ception(From f(); static void g() f(); public static void main(String args) g(); /: The output is:Exception in thread mainjava.lang.RuntimeException: From f() at NeverCaught.f(NeverCaught.java:9) at NeverCaught.g(NeverCaught.java:12) at NeverCaught.main(NeverCaught.java:15)So the answer is: If a Run

29、timeException gets all the way out to main( ) without being caught, printStackTrace( ) is called for that exception as the program exits.26Performing cleanup with finallyTheresoftensomepieceofcodethatyouwanttoexecutewhetherornotanexceptionisthrownwithinatryblock.try / The guarded region: Dangerous a

30、ctivities / that might throw A, B, or C catch(A a1) / Handler for situation A catch(B b1) / Handler for situation B catch(C c1) / Handler for situation C finally / Activities that happen every time 27Tryxxxxxxxxxxthrow xxx or calls a method in which throwsxxxxxxxxxxcatch()yyyyyyfinallyzzzzzz28Perfor

31、ming cleanup with finally29Performing cleanup with finally30Exception restrictionsvWhenyouoverrideamethod,youcanthrowonlytheexceptionsthathavebeenspecifiedinthebase-classversionofthemethod.Thisisausefulrestriction,sinceitmeansthatcodethatworkswiththebaseclasswillautomaticallyworkwithanyobjectderived

32、fromthebaseclass,includingexceptions.vTheexceptionspecificationsarenotpartofthetypeofamethod,Therefore,youcannotoverloadmethodsbasedonexceptionspecifications.vAnexceptionspecificationexistsinabase-classversionofamethoddoesntmeanthatitmustexistinthederived-classversionofthemethod.thisispreciselytheop

33、positeoftherulefortheclassinterfaceduringinheritance.31Exception restrictionsvTherestrictiononexceptionsdoesnotapplytoconstructors.Theconstructorofasubclasscanthrowanythingitwants,regardlessofwhatthebase-classconstructorthrows.vNotethataderived-classconstructorcannotcatchexceptionsthrownbyitsbase-cl

34、assconstructor.Sinceabase-classconstructormustalwaysbecalledonewayoranother,thederived-classconstructormustdeclareanybase-classconstructorexceptionsinitsexceptionspecification.32Exception matching33Exercises4.Defineanobjectreferenceandinitializeittonull.Trytocallamethodthroughthisreference.Nowwrapth

35、ecodeinatry-catchclausetocatchtheexception.6.Createthreenewtypesofexceptions.Writeaclasswithamethodthatthrowsallthree.Inmain(),callthemethodbutonlyuseasinglecatchclausethatwillcatchallthreetypesofexceptions.34SummaryvExceptions are integral to programming with Java; you can accomplish only so much w

36、ithout knowing how to work with them. For that reason, exceptions are introduced at this point in the bookthere are many libraries (like I/O, mentioned earlier) that you cant use without handling exceptions.vBasic exceptionsvThrow an exceptionvCatching an exceptionvCreating your own exceptionsvThe exception specificationvStandard Java exceptionsvThe special case of RuntimeExceptionvPerforming cleanup with finallyvException restrictionsvException matchingvExercises

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 高等教育 > 研究生课件

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号