try-with-resource错误使用导致异常日志丢失

本文讨论了在Java中使用try-with-resources语法时,如果在finally块中执行的close方法先于catch块捕获异常,可能导致异常日志丢失的问题,以及如何避免这种情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

日志工具利用try-with-resources语法在close重载中实现自动计时,错误使用导致日志丢失

精简代码如下:

import cn.hutool.json.JSONUtil;

public class LogHelper implements AutoCloseable {

    public LogHelper(ActionLog actionLog) {
        actionLog.startTime = System.currentTimeMillis();
        this.actionLog = actionLog;
    }

    private ActionLog actionLog;

    @Override
    public void close() throws Exception {
        System.out.println("close执行");
        actionLog.endTime = System.currentTimeMillis();
        actionLog.spendTime = (actionLog.endTime - actionLog.startTime) / 1000;
        actionLog.write();
    }

    static class ActionLog {
        public String message;
        public Long startTime;
        public Long endTime;
        public Long spendTime;
        public Throwable throwable;

        public void write() {
            System.out.println(JSONUtil.toJsonStr(this));
        }
    }

    //测试异常日志打印
    public static void main(String[] args) {
        ActionLog actionLog = new ActionLog();
        try(LogHelper logHelper = new LogHelper(actionLog)) {
            actionLog.message = "log message";
            int a = 1 / 0;
        } catch (Throwable throwable) {
            //close先于catch执行导致异常日志缺失
            System.out.println("catch执行");
            actionLog.throwable = throwable;
        }
    }
}

发生异常时执行结果:

close执行
{"message":"log message","startTime":1711450365630,"endTime":1711450365630,"spendTime":0}
catch执行

可以看到,try-with-resources语句中出现异常时,close语句会先于catch语句执行,导致日志提前打印,丢失了异常信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值