1、1,第六章 例外处理, 例外(Exception)的概念例外处理自定义例外,2,1 public class HelloWorld 2 public static void main(String args ) 3 int i=0; 4 String greetings = “Hello World!”,”Hello!”, 5 “HELLO WORLD!”; 6 while ( i4) 7 System.out.println(greetingsi); 8 i+; 9 10 11 ,Hello World! Hello! HELLO WORLD! Java.lang.ArrayIndexOut
2、OfBoundsExceptionat HelloWorld.main(HelloWorld.java:7),3,Exception 的概念, Exception 是在程序运行时打断正常程序流程的 异常的情况 试图打开的文件不存在 网络链接中断 操作符越界 要加载类文件不存在 Java中定义了各种例外,4,Java中定义了各种例外。Java.lang.Throwable是这些类的父类。,Throwable,Error,Exception,VirtualMachineError,AWTError,RuntimeException,IOException,EOFException,FileNotF
3、oundException,ArithmeticException,NullPointerException,IndexOutOfBoundsException,Java中定义的例外,5, Error描述了Java运行时系统的内部错误和资源耗尽错误。这是很难恢复的严重错误,一般不由程序处理。 RuntimeException由程序错误导致的异常。主要是由于程序设计或实现上的问题,如数组越界、错误的类型转换等。其它例外通常是由环境因素引起的,并且可以被处理的。如试图在文件尾部后面读取数据。试图打开一个不存在的文件,无效URL等。,6,例外处理,捕获并处理例外将方法中产生的例外抛出,7,示例:Li
4、stOfNumbers,import java.io.*; import java.util.Vector; public class ListOfNumbers private Vector victor; private static final int size = 10;public ListOfNumbers () victor = new Vector(size);for (int i = 0; i size; i+)victor.addElement(new Integer(i); public void writeList() printWriter out = new Pri
5、ntWriter(new FileWriter(“OutFile.txt“);for (int i = 0; i size; i+)out.println(“Value at: “ + i + “ = “ + victor.elementAt(i);out.close(); ,8,捕获与处理例外,Try 语句块 catch 语句块 finally 语句块,9,Try语句块,一般形式:try Java statements /一条或多条可能产生例外的java语句。 try 语句后必须跟随至少一个catch或finally语句块。,10,Catch语句块, Catch语句块提供错误处理。 一般格式
6、: catch (SomeThrowableObject variableName) Java statements SomeThrowableObject:能够被处理的例外类名,必须是Throwable类的子类 variableName: 是例外处理程序中能够引用的代表被扑获例外的变量名称。 Java statements: 当扑获到例外时执行的java语句。,11,Finally语句块,将先前方法的状态清除,并可以将控制转移到程序的其他地方。 finally 语句块无论是否发生异常都要执行。,12,例外处理Try ,catch和finally 语句,1 Try 2 / code that
7、might throw a partcular exception 3 catch(MyExceptionType e) 4 / code to excute if a MyExceptionType exception is thrown 5 catch (Exception e) 6 / code to execute if a general Exception exception is thrown 7 finally,13,public void writeList() PrintWriter out = null;try System.out.println(“Entering t
8、ry statement“);out = new PrintWriter( new FileWriter(“OutFile.txt“);for (int i = 0; i size; i+)out.println(“Value at: “ + i + “ = “ + victor.elementAt(i); catch (ArrayIndexOutOfBoundsException e) System.err.println(“Caught ArrayIndexOutOfBoundsException: “ +e.getMessage(); catch (IOException e) Syst
9、em.err.println(“Caught IOException: “ + e.getMessage(); finally if (out != null) System.out.println(“Closing PrintWriter“);out.close(); else System.out.println(“PrintWriter not open“); ,14,writeList方法中的try语句块的执行可能有三种情况: 出现了IOException出现了数组越界错误正常退出,Entering try statementCaught IOException: OutFile.tx
10、tPrintWriter not open,Entering try statement Caught ArrayIndexOutOfBoundsException: 10 = 10 Closing PrintWriter,Entering try statementClosing PrintWriter,15,多种例外的同时处理,16,例外处理可以针对这个体系中的任意一个类。 叶结点:是具体、专用的例外处理; 中间结点:是通用的例外处理。可以处理该结点及其子类类型的例外。,例:writeList 方法: try . . . catch (Exception e) System.err.pri
11、ntln(“Exception caught: “ + e.getMessage(); ,17,捕获与处理例外示例,Public static void main(String args)int i = 0 ;String greetings=“Hello World!”,”Hello!”,”HELLO!”;while (i4)try System.out.println(greetingsi);catch(ArrayIndexOutOfBoundsException e)System.out.println(“Re-setting Index Value”);i=-1;finallySyst
12、em.out.println(“This is always printed”);i+; ,Hello World! This is always printed Hello! This is always printed HELLO! This is always printed Re-setting Index Value This is always printed,18,例外处理抛出例外,可能产生例外的方法表明将不处理该例外,而该例外将被抛到调用该方法的程序。 例:public void troublesome( ) throws IOException 如果一个例外在返回到main(
13、)时还未被处理,则程序将非正常终止。,19,例: public Object pop() throws EmptyStackException Object obj;if (size = 0)throw new EmptyStackException();obj = objectAt(size - 1);setObjectAt(size - 1, null);size-;return obj; 抛出例外的throw语句: throw someThrowableObject,例外处理抛出例外,20,自定义例外,习惯上,定义的类应该包含两个构造器,一个是默认的构造器,另一个是带有详细描述信息的构造
14、器 class MyException extends Exceptionpublic MyException()public MyException(String errMsg)super(errMsg);,21,public class Throwtest public static void main(String args) System.out.println(“Input your age:“); Scanner in=new Scanner(System.in); try int age=in.nextInt(); if(age200) throw new MyException
15、(“The age you input is imposible!“); catch(MyException e) System.out.println(e.getMessage(); ,22,自定义例外,定义例外类,是Exception类的子类,可包含普通类的内容。 public class ServerTimeOutException extends Exceptionprivate String reason;private int port ;public ServerTimeOutException(String reason, int port)this.reason = reas
16、on;this.port = port;public String getReason()return reason;public int getPort()return port; ,23,抛出产生的例外,Public void connectMe(String serverName) throwsServerTimeOutExceptionint success ;int portToConnect = 80;success = open(serverName, portToConnect);if(success= -1)throw new ServerTimedOutException(“Could not connect”,80);,24,获得例外并处理,Public void findServer()tryconnectMe(defaultServer);catch(ServerTimeOutException e)System.out.println(“Server timed out, try another”);tryconnectMe(alternateServer);catch(ServerTimeOutException e1)System.out.println(“No server avaliable”);,