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()抛出,导致最终结果是线程退出,主程序退出。