Java的异常处理细节

规则一

对于try里面发生的异常,它会根据发生的异常和catch里面的进行匹配:按照catch块从上往下匹配,当它匹配某个catch块的时候,就直接进入到这个catch块里面去了,而忽略后面所有的catch块。

规则二

另外:在写异常处理的时候,一定要把异常范围小的放在前面,范围大的放在后面,即如果多个catch块中的异常出现继承关系,子类异常catch块放在上面(否则,连编译都都法通过)

规则三

finally块里的代码是在return之前执行的,如果try-catch-finally中都有return,那么finally块中的return将会覆盖别处的return语句,最终返回到调到者那里
的是finally中return的值。

规则四

在try/catch中有return时,在finally块中改变基本类型的数据对返回值没有任何影响;而在finally中改变引用类型的数据会对返回结果有影响

/**
  execute testFinally1
 1
 execute testFinally2
 helloworld
 */
public class Test {
    
    
    public static int testFinally1() {
        int result1 = 1;
        try {
            return result1;
        } catch (Exception ex) {
            result1 = 2;
            return result1;
        } finally {
            result1 = 3;
            System.out.println("execute testFinally1");
        }
    }

    public static StringBuffer testFinally2() {
        StringBuffer result2 = new StringBuffer("hello");
        try {
            return result2;
        } catch (Exception ex) {
            return null;
        } finally {
            result2.append("world");
            System.out.println("execute testFinally2");
        }
    }
    public static void main(String[] args) {
        int test1 = testFinally1();
        System.out.println(test1);
        StringBuffer test2 = testFinally2();
        System.out.println(test2);
    }
}

猜你喜欢

转载自blog.csdn.net/liudashuang2017/article/details/79992601
今日推荐