为什么“记录并抛出"?被认为是反模式? [英] Why is "log and throw" considered an anti-pattern?

查看:63
本文介绍了为什么“记录并抛出"?被认为是反模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是由围绕

This question was sparked by a discussion around this article, where I did not receive any good answers.

如果不能以其他方式处理异常,为什么不应该记录您的异常然后将其重新抛出(当然,保留原始堆栈跟踪)呢?

推荐答案

我认为答案主要是因为如果无法处理,为什么要抓住它?如果他们认为值得日志,为什么不让任何人可以处理它(或者让别无选择的人处理它)记录下来呢?

I assume the answer is largely because why are you catching it if you can't handle it? Why not let whomever can handle it (or whomever is left with no choice but to handle it) log it, if they feel that it is log-worthy?

如果捕获并记录并重新抛出它,那么上游代码将无法知道您已经记录了该异常,因此相同的异常可能会记录两次.或更糟糕的是,如果所有上游代码都遵循相同的模式,则异常可能会被记录任意次,对于决定捕获该异常,记录该异常然后再次抛出该异常的代码中的每个级别都记录一次.

If you catch it and log it and rethrow it, then there's no way for the upstream code to know that you've already logged the exception, and so the same exception might get logged twice. Or worse, if all the upstream code follows this same pattern, the exception might be logged an arbitrary number of times, once for each level in the code that decides to catch it, log it, and then throw it again.

还有人可能会争辩说,由于抛出和捕获异常是相对昂贵的操作,因此所有这些捕获和重新抛出都无助于提高运行时性能.简洁或可维护性也无济于事.

Also some might argue that since throwing and catching exceptions are relatively costly operations, all this catching and rethrowing isn't helping your runtime performance. Nor is it helping your code in terms of conciseness or maintainability.

这篇关于为什么“记录并抛出"?被认为是反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆