java - 尝试在 Java 中两次处理异常
问题描述
我正在尝试处理异常 2 次
第一个是定义方法的核心:
Class Class1 {
public int method (int a, String b) {
try {
System.out.println(a+" "+b.length());
}
catch (NullPointerException e) {
// TODO: handle exception
System.out.println("catch from the method");
}
finally {
System.out.println("finally from the method");
}
return 0;
}
}
第二个
当我在 main 中调用此方法并将 null 参数传递给它时:
public Class Class2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Class1 c = null;
try {
c = new Class1();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
c.method(1, null);
}
catch (Exception e) {
// TODO: handle exception
System.out.println("catch from the main");
}
finally {
System.out.println("finally from the main");
}
System.out.println("\nEnd of the main");
}
}
结果是:
从方法中捕获
最后从方法
终于从主
主线结束
现在我的问题是,为什么 main 中的 catch 块没有被执行?
解决方案
一旦你捕捉到一个异常,它就不会再进一步了,但你可以再次抛出它。如果您希望您的 main 也看到异常,则需要在捕获异常后再次抛出异常。尝试这个:
public int method (int a, String b) throws NullPointerException{
try {
System.out.println(a+" "+b.length());
}
catch (NullPointerException e) {
// TODO: handle exception
System.out.println("catch from the method");
throw e;
}
finally {
System.out.println("finally from the method");
}
return 0;
}
请注意,由于现在函数中有一个 throw,您需要将其包含在函数定义中
编辑:正如几个人所说,NullPointerException 并不真正需要被捕获,因为它是一个未经检查的异常。这是因为它是 RuntimeException 的子类。
推荐阅读
- python - 如何在 Python 中临时保存数据?
- azure - 到 Databricks 笔记本的 Azure Logic 连接器
- spring-boot - Keycloak Ouath2 集成在 spring cloud dataflow 2.3.0 中不起作用
- swift - 使用编程约束创建视图会导致内容绘制在错误的位置
- javascript - 无法在 javascript 文件 user.js(控制器)中导入我的 mongo 架构文件 order.js(模型)之一
- swift - 正则表达式在每个新行替换空格
- python-3.x - Python ROI 未从轮廓正确裁剪
- excel - 是什么让自定义功能区回调停止工作
- python - 检测周期性的自相关
- midi - 使用带有 partitionByInstrument() 的 music21 读取 MIDI 文件以获取返回空列表的音符和和弦