java - 内部 catch 块引发的异常会发生什么
问题描述
当我运行以下 java 代码时,我得到的输出为“ACDF”。有人可以解释一下如何处理最里面的 catch 块中抛出的运行时异常吗?(我期待它在“E”被附加到结果字符串变量的块中处理)
public class HelloWorld {
public static String someFunction() {
String result = "";
String str = null;
try {
try {
try {
result += "A";
str.length();
result += "B";
} catch (NullPointerException e) {
result += "C";
throw new RuntimeException(); // where this one goes????
} finally {
result += "D";
throw new Exception();
}
} catch (RuntimeException e) {
result += "E";
}
} catch (Exception e) {
result += "F";
}
return result;
}
public static void main(String[] args) {
System.out.println(someFunction());
}
}
解决方案
finally
总是被执行(忽略整个 JVM 死掉的特殊边缘情况)。我不是在开玩笑,即使你return
,也会在之前被处决return
。
请参阅是否总是在 Java 中执行 finally 块?详情。
所以当你抛出时RuntimeException
,你将首先执行finally
附加的那个D
。
既然你扔Exception
在那里,你现在会碰到catch (Exception e)
块,因为catch (RuntimeException e)
不匹配。因此,您追加F
.
因此,结果是ACDF
。
注释代码:
public class HelloWorld {
public static String someFunction() {
String result = "";
String str = null;
try {
try {
try {
result += "A";
str.length(); // throws NullPointerException
result += "B";
} catch (NullPointerException e) { // continue here
result += "C";
throw new RuntimeException();
} finally { // finally is always executed
result += "D";
throw new Exception(); // throwing this
}
} catch (RuntimeException e) { // does not match
result += "E";
}
} catch (Exception e) { // matches, continue here
result += "F";
} // cool, all done
return result; // returning ACDF
}
public static void main(String[] args) {
System.out.println(someFunction());
}
}
推荐阅读
- html - VBA网络抓取:单击列表元素
- java - 在命令行中创建一个 Eclipse Java 项目
- html - 响应高度不起作用,无法找到正确答案
- python - 如何将 numpy 与指向用户名特定 numpy 数组的字符串标识符一起使用
- java - 如何忽略空的 EditText?
- python - 检查字典数组的键值对并相应地更新另一个列表
- php - 无法访问树枝模板 symfony 4 中的布尔值
- javascript - JavaScript 滚动条看起来不像它应该的样子
- python - 如何在 python 中用 open(namefile.txt, w) 编写单独的行?
- c# - 如何使用 Moq 框架模拟一个简单的方法?