Try Catch Finally

看两段代码发现问题所在:

    public static void main(String[] args) {
        Log log = null;
        try {
            throw new Exception();
        }
        catch(Exception e) {
            System.out.println("test2");
            deal(log);
        } finally {
            // 此时log依然为null, 此处访问就会抛出异常NullPointerException
            System.out.println(log.getMessage());
        }
    }
    public static void deal(Log log) {
        if(log == null) {
            log = new Log();
        }
        log.setMessage("00");
    }
    public static void main(String[] args) {
        Log log = null;
        try {
            throw new Exception();
        }
        catch(Exception e) {
            System.out.println("test2");

            if(log == null) {
                log = new Log();
            }
            log.setMessage("00");
        } finally {
            // 此时log不为null, 会打印出00
            System.out.println(log.getMessage());
        }
    }
路慢慢其休远羲,吾将上下而求所
原文地址:https://www.cnblogs.com/garinzhang/p/2946395.html