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());
        }
    }

 

posted @ 2013-03-06 16:45  我是小菜鸟  阅读(179)  评论(0编辑  收藏  举报