Java异常捕获之一道try-catch-finally语句题
今天,学习了try-catch-finally语句,本来觉得蛮简单、易懂的。搜了一道相关类型的题。结果信心被泼了盆冷水。先把题Mark一下,出去透透风。
1 public class TestEx { 2 private int c; 3 4 public TestEx() { 5 } 6 7 @SuppressWarnings("finally") 8 boolean testEx() throws Exception { 9 boolean ret = true; 10 try { 11 ret = testEx1(); 12 } catch (Exception e) { 13 System.out.println("testEx, catch exception"); 14 ret = false; 15 throw e; 16 } finally { 17 System.out.println("testEx, finally; return value=" + ret); 18 return ret; 19 } 20 } 21 22 @SuppressWarnings("finally") 23 boolean testEx1() throws Exception { 24 boolean ret = true; 25 try { 26 ret = testEx2(); 27 if (!ret) { 28 return false; 29 } 30 System.out.println("testEx1, at the end of try"); 31 return ret; 32 } catch (Exception e) { 33 System.out.println("testEx1, catch exception"); 34 ret = false; 35 throw e; 36 } finally { 37 System.out.println("testEx1, finally; return value=" + ret); 38 return ret; 39 } 40 } 41 42 @SuppressWarnings("finally") 43 boolean testEx2() throws Exception { 44 boolean ret = true; 45 try { 46 int b = 12; 47 for (int i = 2; i >= -2; i--) { 48 setC(b / i); 49 System.out.println("i=" + i); 50 } 51 return true; 52 } catch (Exception e) { 53 System.out.println("testEx2, catch exception"); 54 ret = false; 55 throw e; 56 } finally { 57 System.out.println("testEx2, finally; return value=" + ret); 58 return ret; 59 } 60 } 61 62 public static void main(String[] args) { 63 TestEx testException1 = new TestEx(); 64 try { 65 testException1.testEx(); 66 } catch (Exception e) { 67 e.printStackTrace(); 68 } 69 } 70 71 public int getC() { 72 return c; 73 } 74 75 public void setC(int c) { 76 this.c = c; 77 } 78 }
Output:
看完之后我就在想,
1.Java异常处理机制,我真的理解了吗?
2.Java异常处理,我真的掌握了吗?
3.catch体里遇到return 是怎么处理?
4.finally 体里有return怎么处理?
5. catch 和 finally 体里同时遇上 return 怎么办?
6.是不是还有个System.exit()?遇到它又咋办??
7.仅仅知道throws不是完全之策啊,还要继续深入理解啊。2017-06-1918:21:08
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程