何时为捕获的异常记录堆栈跟踪 [英] When to log a stacktrace for a caught exception
问题描述
我最近问是否报告getMessage()
捕获异常的文本.相当令人惊讶的是,大多数答案都误解了我的问题,并认为我是在问是否要报告捕获异常的堆栈跟踪,这表明这样做被认为是常态.所以我要问一个后续问题.
I recently asked whether to report the getMessage()
text of a caught exception. Rather surprisingly, most answers misunderstood my question and thought I was asking whether to report the stack-trace for a caught exception, suggesting that doing so is considered the norm. So I'm asking a follow up question.
在什么情况下,当您catch
异常时,您应该还是不应该报告堆栈跟踪?通过报告",我包括询问日志框架为您记录堆栈跟踪.
In which circumstances should you, or should you not, report a stack-trace when you catch
an exception? By "reporting" I include asking a logging framework to log the stack-trace for you.
我不是在问是否要报告某事.我在问那个报告是否应该包括堆栈跟踪.
I am not asking whether to report something. I'm asking whether that report should include the stack-trace.
推荐答案
我个人尝试遵守这些规则:
I personally try to obey these rules:
如果我可以以可恢复"的方式处理 catch 中的异常(例如 DateFormatException),则无需跟踪堆栈
if I can handle the exception in the catch in a 'recoverable' way (e.g. a DateFormatException), no need to trace the stack
如果我想重新抛出异常,请不要记录堆栈跟踪.(以链式方式重新抛出以保留此信息)
if I want to rethrow the exception, log no stack trace. (rethrow in a chained way to retain this information)
如果我将 catch 块中的异常作为错误情况(例如 sql 错误)处理,我会记录堆栈跟踪.
if I handle the exception in a catch block as an error case (e.g. sql error), I log the stack trace.
如果是运行时异常,我建议框架(您的或您使用的任何框架)进行跟踪.
if it's a runtime exception, I would suggest the framework (yours or whatever you use) does the tracing.
这篇关于何时为捕获的异常记录堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!