我正在为OCA考试做准备,在解决有关Java异常的问题时,我发现了一个冲突点。下面是引起我困惑的代码:
public class StringOps {
public static void main(String[] args) {
System.out.print("a");
try {
System.out.print("b");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.print("c");
throw new RuntimeException("1");
} catch (RuntimeException e) {
System.out.print("d");
throw new RuntimeException("2");
} finally {
System.out.print("e");
throw new RuntimeException("3");
}
}
}此代码输出:a-> b -> c -> e。
但我不明白为什么?我以为它会输出:a-> b -> c -> d -> e。
任何帮助都将不胜感激!
发布于 2018-09-26 05:54:22
这是因为即使在第一个catch块中抛出了一个新的RuntimeException,这个新的RuntimeException仍然受第一个catch块中的子句的约束。
如果你想尝试多个捕获,你必须嵌套你的/。控制流始终是:
try --> catch --> finally.希望这能有所帮助!
https://stackoverflow.com/questions/52506802
复制相似问题