在try / catch块中包装所有内容都构成防御性编程? [英] Does wrapping everything in try/catch blocks constitute defensive programming?
问题描述
我的基本规则是:除非您可以强>引起异常的问题,不要抓住它,让它起泡到可以处理的水平。
根据我的经验,95%的所有catch块都只是忽略异常( catch {}
),或者只是记录错误并重新抛出异常。后者可能看起来是正确的事情,但实际上,当这在每一个层次都完成时,你最终只会收到同一个错误消息的五个副本的日志。通常,这些应用程序在最高级别(因为我们尝试/捕获所有较低级别)都有一个忽略捕获),导致一个非常慢的应用程序,有很多错过的异常,以及错误日志太长任何人愿意透过它。
I have been programming for the last 3 years. When I program, I use to handle all known exceptions and alert the user gracefully. I have seen some code recently which has almost all methods wrapped inside try/catch blocks. The author says it is part of defensive programming. I wonder, is this really defensive programming? Do you recommend putting all your code in try blocks?
My basic rule is : Unless you can fix the problem which caused the exception, do not catch it, let it bubble up to a level where it can be dealt with.
In my experience, 95% of all catch blocks either just ignore the exception (catch {}
) or merely log the error and rethrow the exception. The latter might seem like the right thing to do, but in practice, when this is done at every level, you merely end up with your log cluttered with five copies of the same error message. Usually these apps have an "ignore catch" at the top most level (since "we have try/catch at all the lower levels"), resulting in a very slow app with lots of missed exceptions, and an error log that too long for anyone to be willing to look through it.
这篇关于在try / catch块中包装所有内容都构成防御性编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!