2019-11-02一、1.异常:软件程序在运行过程中,可能出现一些例外(Exception)的情况。
2.java是采用面向对象的方法来处理异常的,处理过程:
抛出异常:在执行一个方法时,如果发生异常,则这个方法生成代表该异常的一个对象,停止当前执行路径,并把异常对象提交给JRE。
捕获异常:JRE得到该异常后,寻找相应的代码来处理该异常。JRE在方法的调用栈中查找,从生成异常的方法开始回溯,直到找到相应的异常处理代码为止。
处理:try{...}catch{...}finally{...}
try里面放可能会发生错误的代码,若出现错误则抛出一个异常对象,下面catch进行捕获,进行异常的处理。finally里放用于“善后”的代码,不管是否有异常发生finally始终被执行。如果没有提供合适的异常处理机制,JVM将会结束掉整个应用程序。
二、异常分类:
JDK中定义了很多异常类,这些类对应了各种各样可能出现的异常事件,所有异常对象都是派生于Throwable类的一个实例。除此,还可以创建自己的异常类。所有异常的根为java.lang.Throwable,Throwable下面有派生了两个子类:Error(系统错误,通常由JVM处理)和Exception(出现的问题是可以被捕获的)。可捕获的异常又可以分为两类:(1)Check异常:直接派生自Exception的异常类,必须被捕获或再次声明抛出;(2)Runtime异常:派生自RuntimeException的异常类。使用throw语句可以随时抛出这种异常对象。
三、多层的异常捕获
package org.yuan.Day3; public class CatchWho { public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch"); } throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("发生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch"); } } }
运行结果:
package org.yuan.Day3; public class CatchWho2 { public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArithmeticException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch"); } throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("发生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch"); } } }
运行结果:
只有抛出的异常被捕获后才能抛出另一个异常
package org.yuan.Day3; public class EmbededFinally { public static void main(String args[]) { int result; try { System.out.println("in Level 1"); try { System.out.println("in Level 2"); // result=100/0; //Level 2 try { System.out.println("in Level 3"); result=100/0; //Level 3 } catch (Exception e) { System.out.println("Level 3:" + e.getClass().toString()); } finally { System.out.println("In Level 3 finally"); } // result=100/0; //Level 2 } catch (Exception e) { System.out.println("Level 2:" + e.getClass().toString()); } finally { System.out.println("In Level 2 finally"); } // result = 100 / 0; //level 1 } catch (Exception e) { System.out.println("Level 1:" + e.getClass().toString()); } finally { System.out.println("In Level 1 finally"); } } }
运行结果:
当有多层嵌套的finally时,异常在不同的层次抛出,在不同的位置抛出,可能会导致不同的finally语句块执行顺序。