标签:
1 // Demonstrate multiple catch statements. 2 class MultiCatch { 3 public static void main(String args[]) { 4 try { 5 int a = args.length; 6 System.out.println("a = " + a); 7 int b = 42 / a; 8 int c[] = { 1 }; 9 c[42] = 99; 10 } catch(ArithmeticException e) { 11 System.out.println("Divide by 0: " + e); 12 } catch(ArrayIndexOutOfBoundsException e) { 13 System.out.println("Array index oob: " + e); 14 } 15 System.out.println("After try/catch blocks."); 16 } 17 }
该程序在没有命令行参数的起始条件下运行导致被零除异常,因为a为0。如果你提供一个命令行参数,它将幸免于难,把a设成大于零的数值。但是它将导致ArrayIndexOutOf BoundsException异常,因为整型数组c的长度为1,而程序试图给c[42]赋值。
1 /* This program contains an error. 2 A subclass must come before its superclass in a series of catch statements. If not,unreachable code will be created and acompile-time error will result. 3 */ 4 class SuperSubCatch { 5 public static void main(String args[]) { 6 try { 7 int a = 0; 8 int b = 42 / a; 9 } catch(Exception e) { 10 System.out.println("Generic Exception catch."); 11 } 12 /* This catch is never reached because 13 ArithmeticException is a subclass of Exception. */ 14 catch(ArithmeticException e) { // ERROR - unreachable 15 System.out.println("This is never reached."); 16 } 17 } 18 }
如果你试着编译该程序,你会收到一个错误消息,该错误消息说明第二个catch语句不会到达,因为该异常已经被捕获。因为ArithmeticException 是Exception的子类,第一个catch语句将处理所有的面向Exception的错误,包括ArithmeticException。这意味着第二个catch语句永远不会执行。为修改程序,颠倒两个catch语句的次序。
标签:
原文地址:http://www.cnblogs.com/Coda/p/4464455.html