资源预览内容
第1页 / 共34页
第2页 / 共34页
第3页 / 共34页
第4页 / 共34页
第5页 / 共34页
第6页 / 共34页
第7页 / 共34页
第8页 / 共34页
第9页 / 共34页
第10页 / 共34页
亲,该文档总共34页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
1 1Chapter 12Error Handling with Exceptions2Why?人非圣贤,孰能无过。人非圣贤,孰能无过。过而能改,善莫大焉。过而能改,善莫大焉。3Basic exceptionsvErrorsalwaysoccurinsoftwareprograms.Whatreallymattersis:Howistheerrorhandled?Whohandlesit?Cantheprogramrecover,orjustprinterrormessagesandexit?InCandotherearlierlanguages,youreturnedaspecialvalueorsetaflag,andtherecipientwassupposedtolookatthevalueortheflagtodetermineifsomethingwaswrong.TheJavaprogramminglanguageusesexceptionsforerrorhandling.Errorcompile-time Errorrun-time Error4int readFile initialize errorCode = 0; open the file; if (theFileIsOpen) determine the length of the file; if (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 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 (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 RuntimeExceptionvPerforming cleanup with finallyvException restrictionsvException matchingvExercises7Whats an Exception vThetermexceptionisshorthandforthephraseexceptionalevent.Definition:Anexceptionisaneventthatoccursduringtheexecutionofaprogramthatdisruptsthenormalflowofinstructions.Classification:ExceptionandErrorvHowtodistinguishanexceptionalconditionfromanormalproblem:Normalproblem:whenyouhaveenoughinformationinthecurrentcontexttosomehowcopewiththedifficulty.Exceptionalcondition:youcannotcontinueprocessingbecauseyoudonthavetheinformationnecessarytodealwiththeproblemin the current context.Allyoucandoisjumpoutofthecurrentcontextandrelegatethatproblemtoahighercontext.Thisiswhathappenswhenyouthrowanexception.vAsimpleexampleisadivide.Ifyoureabouttodividebyzero,itsworthcheckingtomakesureyoudontgoaheadandperformthedivide.Butwhatdoesitmeanthatthedenominatoriszero?8Throwable RuntimeException,IOException,ArithmeticException,FileNotFoundException,OutOfMemoryException,ArrayIndexOutofBoundsException,NullPointerExceptionAbstractMethodError,IllegalAccessError,InternalError,NoClassDefFoundError,NoSuchMethodError,OutOfMemoryError,AWTError,UnknownErrorExceptionErrorObject Whats an Exception 9Throw an ExceptionvTherearetwoconstructorsinallstandardexceptions:thefirstisthedefaultconstructor,andthesecondtakesastringargumentsoyoucanplacepertinentinformationintheexception:if(t = null) throwthrow new NullPointerException(); if(t = null) throwthrow new NullPointerException(t = null); 10class TooBig extends 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 exceptionvWhendoesanexceptionoccur?WhenyouthrowanexceptionOranothermethodyoucallthrowsanexceptionvIfyoureinsideamethodandanexceptionoccurs,thatmethodwillexitintheprocessofthrowing.vIfyoudontwanttoexitthemethod,youcansetupaspecialblocktocapturetheexception.Thisiscalledthetryblock.12Catching an exceptiontry / Code that might 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,theexceptionhandlingmechanismgoeshuntingforthefirsthandlerthatmatchesthetypeoftheexception.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(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) 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 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( 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 17The exception specificationvInJava,yourerequiredtoinformtheclientprogrammer,whocallsyourmethod,oftheexceptionsthatmightbethrownfromyourmethod.vTheexceptionspecificationusesanadditionalkeyword,throws,followedbyalistofallthepotentialexceptiontypes.void f() throwsthrows TooBig, TooSmall, DivZero /. Ifyousayvoid f() / . vitmeansthatnoexceptionsarethrownfromthemethod.(Except fortheexceptionsoftypeRuntimeException,whichcanreasonablybethrownanywherethiswillbedescribedlater.)18Catching any exceptionvBycatchingthebase-classexceptiontypeException,itispossibletocreateahandlerthatcatchesanytypeofexception.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( ) -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 Exception(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.printStackTrace(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 exceptionsvTheJavaclassThrowabledescribesanythingthatcanbethrownasanexception.23The special case of RuntimeException)JavawillautomaticallythrowaNullPointerException.if(t = null) throw new NullPointerException();else t.somefunc();theabovebitofcodeequalsto: t.somefunc();24The special case of RuntimeException)YouneverneedtowriteanexceptionspecificationsayingthatamethodmightthrowaRuntimeException,sincethatsjustassumed.Becausetheyindicatebugs,youvirtuallynevercatchaRuntimeException )Sincethecompilerdoesntenforceexceptionspecificationsforthese,itsquiteplausiblethataRuntimeExceptioncouldpercolateallthewayouttoyourmain() methodwithoutbeingcaught. ArithmeticException, ClassCastException, llegalArgumentException, IllegalStateException, IndexOutOfBoundsException, NoSuchElementException, NullPointerException, 25The special case of RuntimeExceptionpublic class NeverCaught static void f() throw new RuntimeException(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 RuntimeException 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 activities / 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()yyyyyyfinallyzzzzzz28Performing cleanup with finally29Performing cleanup with finally30Exception restrictionsvWhenyouoverrideamethod,youcanthrowonlytheexceptionsthathavebeenspecifiedinthebase-classversionofthemethod.Thisisausefulrestriction,sinceitmeansthatcodethatworkswiththebaseclasswillautomaticallyworkwithanyobjectderivedfromthebaseclass,includingexceptions.vTheexceptionspecificationsarenotpartofthetypeofamethod,Therefore,youcannotoverloadmethodsbasedonexceptionspecifications.vAnexceptionspecificationexistsinabase-classversionofamethoddoesntmeanthatitmustexistinthederived-classversionofthemethod.thisispreciselytheoppositeoftherulefortheclassinterfaceduringinheritance.31Exception restrictionsvTherestrictiononexceptionsdoesnotapplytoconstructors.Theconstructorofasubclasscanthrowanythingitwants,regardlessofwhatthebase-classconstructorthrows.vNotethataderived-classconstructorcannotcatchexceptionsthrownbyitsbase-classconstructor.Sinceabase-classconstructormustalwaysbecalledonewayoranother,thederived-classconstructormustdeclareanybase-classconstructorexceptionsinitsexceptionspecification.32Exception matching33Exercises4.Defineanobjectreferenceandinitializeittonull.Trytocallamethodthroughthisreference.Nowwrapthecodeinatry-catchclausetocatchtheexception.6.Createthreenewtypesofexceptions.Writeaclasswithamethodthatthrowsallthree.Inmain(),callthemethodbutonlyuseasinglecatchclausethatwillcatchallthreetypesofexceptions.34SummaryvExceptions are integral to programming with Java; you can accomplish only so much without 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
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号