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

        }

    }

 

你可能感兴趣的:(finally)