在try / catch块中包装所有内容都构成防御性编程? [英] Does wrapping everything in try/catch blocks constitute defensive programming?

查看:192
本文介绍了在try / catch块中包装所有内容都构成防御性编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过去3年来一直在编程。当我编程时,我使用来处理所有已知的异常并且优雅地提醒用户。最近看到一些代码包含在try / catch块中的几乎所有的方法。作者说这是防御性程式设计的一部分。我不知道这是真正的防御性编程吗?您是否建议将所有代码放在try块中?

解决方案

我的基本规则是:除非您可以强>引起异常的问题,不要抓住它,让它起泡到可以处理的水平。



根据我的经验,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屋!

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