您好,欢迎访问三七文档
1第九章通过异常处理错误2Exceptions的概念例外处理自定义例外31PublicclassHelloWorld{2publicstaticvoidmain(Stringargs[]){3inti=0;4Stringgreetings[]={“HelloWorld!”,”Hello!”,5“HELLOWORLD!!”};6while(i4){7System.out.println(greetings[i]);8i++;9}10}11}HelloWorld!Hello!HELLOWORLD!Java.lang.ArrayIndexOutOfBoundsExceptionatHelloWorld.main(HelloWorld.java:7)4Exception的概念Exception是在程序运行时打断正常程序流程的异常的情况•试图打开的文件不存在•网络链接中断•操作符越界•要加载类文件不存在Java中定义了各种例外5Java中定义了各种例外。Java.lang.Throwable是这些类的父类。ThrowableErrorExceptionVirtualMachineErrorAWTErrorRuntimeExceptionIOExceptionEOFExceptionFileNotFoundExceptionArithmeticExceptionNullPointerExceptionIndexOutOfBoundsExceptionJava中定义的例外6Error很难恢复的严重错误,一般不由程序处理。RuntimeException程序设计或实现上的问题,如数组越界等。其它例外通常是由环境因素引起的,并且可以被处理的。如文件不存在,无效URL等。7例外处理扑获并处理例外将方法中产生的例外抛出8importjava.io.*;importjava.util.Vector;publicclassListOfNumbers{privateVectorvictor;privatestaticfinalintsize=10;publicListOfNumbers(){victor=newVector(size);for(inti=0;isize;i++)victor.addElement(newInteger(i));}publicvoidwriteList(){printWriterout=newPrintWriter(newFileWriter(OutFile.txt));for(inti=0;isize;i++)out.println(Valueat:+i+=+victor.elementAt(i));out.close();}}示例:ListOfNumbers9捕获与处理例外•Try语句块•catch语句块•finally语句块10Try语句块一般形式:try{Javastatements//一条或多条可能产生例外的java语句。}try语句后必须跟随至少一个catch或finally语句块。11Catch语句块Catch语句块提供错误处理。一般格式:catch(SomeThrowableObjectvariableName){Javastatements}•SomeThrowableObject:能够被处理的例外类名,必须是throwable类的子类•variableName:是例外处理程序中能够引用的代表被捕获例外的变量名称。•Javastatements:当捕获到例外时执行的java语句。12Finally语句块将先前方法的状态清除,并可以将控制转移到程序的其他地方。finally语句块无论是否发生异常都要执行。13例外处理——Try,catch和finally语句1Try{2//codethatmightthrowapartcularexception3}catch(MyExceptionTypee){4//codetoexcuteifaMyExceptionTypeexceptionisthrown5}catch(Exceptione){6//codetoexecuteifageneralExceptionexceptionisthrown7}finally{}14publicvoidwriteList(){PrintWriterout=null;try{System.out.println(Enteringtrystatement);out=newPrintWriter(newFileWriter(OutFile.txt));for(inti=0;isize;i++)out.println(Valueat:+i+=+victor.elementAt(i));}catch(ArrayIndexOutOfBoundsExceptione){System.err.println(CaughtArrayIndexOutOfBoundsException:+e.getMessage());}catch(IOExceptione){System.err.println(CaughtIOException:+e.getMessage());}finally{if(out!=null){System.out.println(ClosingPrintWriter);out.close();}else{System.out.println(PrintWriternotopen);}}}15writeList方法中的try语句块的执行可能有三种情况:•出现了IOException•出现了数组越界错误•正常退出EnteringtrystatementCaughtIOException:OutFile.txtPrintWriternotopenEnteringtrystatementCaughtArrayIndexOutOfBoundsException:10=10ClosingPrintWriterEnteringtrystatementClosingPrintWriter16多种例外的同时处理17例外处理可以针对这个体系中的任意一个类。•叶结点:是具体、专用的例外处理;•中间结点:是通用的例外处理。可以处理该结点及其子类类型的例外。例:writeList方法:try{...}catch(Exceptione){System.err.println(Exceptioncaught:+e.getMessage());}18捕获与处理例外示例Publicstaticvoidmain(Stringargs[]){inti=0;Stringgreetings[]={“HelloWorld!”,”Hello!”,”HELLO!”};while(i4){try{System.out.println(greetings[i]);}catch(ArrayIndexOutOfBoundsExceptione){System.out.println(“Re-settingIndexValue”);i=-1;}finally{System.out.println(“Thisisalwaysprinted”);}i++;}}HelloWorld!ThisisalwaysprintedHello!ThisisalwaysprintedHELLO!ThisisalwaysprintedRe-settingIndexValueThisisalwaysprinted19例外处理——抛出例外可能产生例外的方法表明将不处理该例外,而该例外将被抛到调用该方法的程序。例:publicvoidtroublesome()throwsIOException{…..}如果一个例外在返回到main()时还未被处理,则程序将非正常终止。20例外处理——抛出例外例:publicObjectpop()throwsEmptyStackException{Objectobj;if(size==0)thrownewEmptyStackException();obj=objectAt(size-1);setObjectAt(size-1,null);size--;returnobj;}抛出例外的throw语句:throwsomeThrowableObject21自定义例外定义例外类,是Exception类的子类,可包含普通类的内容。publicclassServerTimeOutExceptionextendsException{privateStringreason;privateintport;publicServerTimeOutException(Stringreason,intport){this.reason=reason;this.port=port;}publicStringgetReason(){returnreason;}publicintgetPort(){returnport;}}22抛出产生的例外PublicvoidconnectMe(StringserverName)throwsServerTimeOutException{intsuccess;intportToConnect=80;success=open(serverName,portToConnect);if(success=-1){thrownewServerTimedOutException(“Couldnotconnect”,80);}}23获得例外并处理PublicvoidfindServer(){…try{connectMe(defaultServer);}catch(ServerTimeOutExceptione){System.out.println(“Servertimedout,tryanother”);try{connectMe(alternateServer);}catch(ServerTimeOutExceptione1){System.out.println(“Noserveravaliable”);}}
本文标题:通过异常处理错误
链接地址:https://www.777doc.com/doc-3090528 .html