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

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

 

相关文章:

  • 2022-12-23
  • 2021-09-23
  • 2021-10-27
  • 2021-09-12
  • 2022-01-31
  • 2021-07-19
猜你喜欢
  • 2022-01-18
  • 2021-10-20
  • 2021-07-14
  • 2021-12-04
  • 2021-10-19
相关资源
相似解决方案