异常处理
异常的“多态”特性
(1)可以有多个catch语句块,每个代码块捕获一种异常。在某个try块后面会有两个不同的catch块捕获两个相同类型的异常是语法错误。
(2)使用catch语句,只能捕获Exception类及其子类的对象。因此,一个捕获Exception对象的catch语句块可以捕获所有“可捕获”的异常。
(3)将catch(Exception e)放在别的catch块前面会使这些catch块都不执行,因此Java不会编译这个程序。
package schoolworld; public class Demo { 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"); } } }
上诉代码的运行结果为
ArrayIndexOutOfBoundsException/内层try-catch
发生ArithmeticException
package schoolworld; public class Demo { 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"); } } }
运行结果为
ArrayIndexOutOfBoundsException/外层try-catch
package schoolworld; public class Demo { public static void main(String[] args) { try{ System.out.println("in main"); throw new Exception("Exception is thrown in main"); //System.exit(0); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } finally { System.out.println("in finally"); } } }
运行结果为
in main
Exception is thrown in main