Craig 已经解决了未处理的异常问题,但我想澄清一下。我编写了两个示例(最后一个很糟糕,因为在发生异常后您可能正在处理断开的连接,请不要这样做)。这是一个引发 ArrayIndexOutOfBoundsException 的简单示例:
class TryCatchFinally {
static int [] array = new int[1];
public static void main(String [] args) throws Exception {
if (args[0].startsWith("1")) {
version1();
} else if (args[0].startsWith("2")) {
version2();
}
}
static int version1() {
int r = 0;
try {
System.out.println("In Try.");
return array[1];
} catch (Exception e) {
System.out.println("In Catch.");
} finally {
System.out.println("In Finally.");
}
System.out.println("In Return.");
return r;
}
static int version2() {
int r = array[1];
try {
System.out.println("In Try.");
} catch (Exception e) {
System.out.println("In Catch.");
} finally {
System.out.println("In Finally.");
}
System.out.println("In Return.");
return r;
}
}
这是执行:
(TryCatchFinally)$ javac *.java
(TryCatchFinally)$ java TryCatchFinally 1
In Try.
In Catch.
In Finally.
In Return.
(TryCatchFinally)$ java TryCatchFinally 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at TryCatchFinally.version2(TryCatchFinally.java:24)
at TryCatchFinally.main(TryCatchFinally.java:7)
(TryCatchFinally)$
正如您在第一个版本中看到的那样,注册了一个异常处理程序,因为异常发生在 try 块的上下文中。在第二个版本中,没有注册的异常处理程序,并且调用了默认的异常处理程序(意味着未捕获的异常)。