try-catch-finally
来源:互联网 发布:电子发票 用软件开 编辑:程序博客网 时间:2024/06/05 14:45
笔试题:
public class Test1 { private static void test(int[]arr) { for (int i = 0; i < arr.length; i++) { try { if (arr[i] % 2 == 0) { throw new NullPointerException(); } else { System.out.print(i); } } catch (Exception e) { System.out.print("a "); } finally { System.out.print("b "); } } } public static void main(String[]args) { try { test(new int[] {0, 1, 2, 3, 4, 5}); } catch (Exception e) { System.out.print("c "); } } }
输出结果: a b 1b a b 3b a b 5b
有catch语句块,由catch处理,函数正常运行;finally始终运行。
public class Test1 { private static void test(int[]arr) { for (int i = 0; i < arr.length; i++) { try { if (arr[i] % 2 == 0) { throw new NullPointerException(); } else { System.out.print(i); } } finally { System.out.print("b "); } } } public static void main(String[]args) { try { test(new int[] {0, 1, 2, 3, 4, 5}); } catch (Exception e) { System.out.print("c "); } } }
输出结果: b c
没有catch语句块,抛出异常,由函数调用者接收并处理该异常,主程序退出。finally依旧是始终运行。
当出现运行时异常是,如果方法体中使用try-catch捕获异常并处理,则方法不会抛出异常,如果没有捕捉并处理,系统会把异常一直往上抛,一直遇到处理代码,如果没有处理快,到最上层,多线程由Thread.run()抛出,如果是单线程就被main()抛出,导致最终结果是线程退出,主程序退出。
阅读全文
0 0
- try..catch..finally
- try-catch-finally
- Try-catch-finally机制
- 关于try-catch-finally
- C# try catch finally
- try...catch...finally
- try catch finally用法
- Try ---Catch----Finally
- try...catch... finally
- try....catch...finally 妙用
- try{} catch(){}finally{}执行
- Try Catch Finally
- try-catch-finally
- C# try, catch ,finally
- try catch finally
- try catch finally
- try-catch-finally
- try...catch...finally
- 快速排序--基准定位,分而治之
- 如何生成war包
- Dagger2的使用与理解(4)
- Ubuntu下安装tools
- STL系列之一 deque双向队列
- try-catch-finally
- ural1109Conference(最小边覆盖)
- Hystrix系列-3-Hystrix的配置-通过代码构造配置
- DHCP配置
- 在一个千万级的数据库查寻中,如何提高查询效率
- 直线距离
- 版本控制:git常用命令
- 【OpenCV入门教程之十六】OpenCV角点检测之Harris角点检测
- shell函数:cut