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]赋值。


下面是运行在两种不同情况下程序的输出:
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks.
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.

当你用多catch语句时,记住异常子类必须在它们任何父类之前使用是很重要的。这是因为运用父类的catch语句将捕获该类型及其所有子类类型的异常。这样,如果子类在父类后面,子类将永远不会到达。而且,Java中不能到达的代码是一个错误。例如,考虑下面的程序:
 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语句的次序。

相关文章: