今天在工作中,我不得不查看一个类似于这个模拟例子的代码片段。终于在例外情况下嵌套的行为
package test;
import java.io.IOException;
import org.apache.log4j.Logger;
public class ExceptionTester {
public static Logger logger = Logger.getLogger(ExceptionTester.class);
public void test() throws IOException {
new IOException();
}
public static void main(String[] args) {
ExceptionTester comparator = new ExceptionTester();
try {
try {
comparator.test();
} finally {
System.out.println("Finally 1");
}
} catch(IOException ex) {
logger.error("Exception happened" ex);
// also close opened resources
}
System.out.println("Exiting out of the program");
}
}
它打印以下output.I预期的编译错误,因为内try
没有一个catch
块。
Finally 1 Exiting out of the program
我不明白为什么IOException
由外catch
块捕获。我将不胜感激,如果任何人都可以解释这一点,尤其是通过引用堆栈展开过程
`try`必须有> = 1`catch` __和/或``finally`。 'catch'不是必需的。 – dkarp 2011-01-12 03:12:16