java 異常抛出 throw 與 return
package 異常;
public class TestException {
public TestException() {
}
boolean testEx() throws Exception {
boolean ret = true;
try {
ret = testEx1();
} catch (Exception e) {
e.printStackTrace();
System.out.println("testEx, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx, finally; return value=" + ret);
return ret;
}
}
boolean testEx1() throws Exception {
boolean ret = true;
try {
ret = testEx2();
if (!ret) {
return false;
}
System.out.println("testEx1, at the end of try");
return ret;
} catch (Exception e) {
e.printStackTrace();
System.out.println("testEx1, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx1, finally; return value=" + ret);
return ret;
}
}
boolean testEx2() throws Exception {
boolean ret = true;
try {
int b = 12;
int c;
for (int i = 2; i >= -2; i--) {
c = b / i;
System.out.println("i=" + i);
}
// return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("testEx2, catch exception");
ret = false;
//極其重要 throw 可以代替 return 若後面 finally 中是 return 調用此方法的將不會收到異常
//(即catch裏面作爲結果抛出的異常被finally裏面的return覆蓋了) 若沒有return也沒有抛出某異常 則調用的將會接到此處抛出的異常並處理
throw e;
} finally {
System.out.println("testEx2, finally; return value=" + ret);
// return ret;
throw new ArrayIndexOutOfBoundsException();
}
// System.out.println("執行中");
// return false;
}
public static void main(String[] args) {
TestException testException1 = new TestException();
try {
testException1.testEx();
} catch (Exception e) {
e.printStackTrace();
System.out.println("main");
}
}
}
結果
i=2
i=1
java.lang.ArithmeticException: / by zero
at 異常.TestException.testEx2(TestException.java:48)
at 異常.TestException.testEx1(TestException.java:25)
at 異常.TestException.testEx(TestException.java:10)
at 異常.TestException.main(TestException.java:71)
testEx2, catch exception
testEx2, finally; return value=false
java.lang.ArrayIndexOutOfBoundsException
at 異常.TestException.testEx2(TestException.java:62)
at 異常.TestException.testEx1(TestException.java:25)
at 異常.TestException.testEx(TestException.java:10)
at 異常.TestException.main(TestException.java:71)
testEx1, catch exception
testEx1, finally; return value=false
testEx, finally; return value=false
如果所有方法都层层上抛获取的异常,最终JVM会进行处理,处理也很简单,就是打印异常消息和堆栈信息
質料 http://www.cnblogs.com/to-creat/p/5688235.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】