使用guard子句或捕捉异常是否更好? [英] Is it better using a guard clause or catching the exception?

查看:107
本文介绍了使用guard子句或捕捉异常是否更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好是用guard子句来防止异常或者捕获异常?
有最好的做法?
两种方法的优点和缺点?



例如更好的是:

  try 
{
param = myArray [3];
}
catch(IndexOutOfRangeException e)
{
做某事...
}

或者这个:

  if(myArray.Length< 4)
{
做某事...
}
else
{
param = myArray [3];
}

感谢大家的答案:)

解决方案


最好是用guard子句来防止异常或者捕获异常吗?


在索引超出范围的骨头异常的情况下,始终为前者。



在外生例外情况下,总是出现这种情况。


两种方法的优缺点? / p>

在头骨异常的情况下,只有后者的缺点。他们是:




  • 与测试相比,例外情况

  • 异常是为了模拟特别罕见的控制流情况;如果可能访问索引超出范围是正常,那么不要写一个异常处理程序。

  • 异常被报告为第一即使异常被处理,监听器也不例外。许多系统 - 例如ASP--聆听第一次机会异常,记录所有这些异常,并将其中的许多组件视为,因为它们是 。 (我曾经在ASP中的一个常见的代码路径中介绍了一个故意的第一次机会异常,一天后我听到了男孩,这个bug子系统测试很疯狂。)

  • 一些例外,我称之为骨头的异常 - 空解引用,索引超出范围等等,因为它们很容易避免,并指示故障显然是危险的,他们应该永远被视为致命的错误,并且永远不会被处理(除非处理程序在关闭进程之前进行了记录。)请勿处理该错误,以消除错误



最后,您应该阅读我关于此主题的文章。



a href =http://ericlippert.com/2008/09/10/vexing-exceptions/> http://ericlippert.com/2008/09/10/vexing-exceptions/


is it better to prevent exception with a guard clause or catch the exception? There is a best practice? Pro and cons of the two methodologies?

For example is better this:

try
{ 
    param=myArray[3];
}
catch (IndexOutOfRangeException e)
{
    do something...
}

or this:

if(myArray.Length < 4)
{
    do something...
}
else
{
    param=myArray[3];
}

Thank you all for the answers :)

解决方案

is it better to prevent exception with a guard clause or catch the exception?

In the case of "boneheaded" exceptions like index out of range, always the former.

In the case of "exogenous" exceptions, always the latter.

Pro and cons of the two methodologies?

There are only cons of the latter in the case of boneheaded exceptions. They are:

  • Exceptions are incredibly expensive compared to tests.
  • Exceptions are intended to model exceptionally rare control flow situations; if potentially accessing an index out of range is normal then don't write an exception handler.
  • Exceptions are reported as "first chance" exceptions to listeners even if the exception is handled. Many systems -- ASP, for example -- listen for first chance exceptions, log all of them, and treat components that produce a lot of them as buggy, because they are. (I once introduced a deliberate first-chance exception in a common code path in ASP and a day later boy did I hear about it. The buggy-subsystem tests went crazy.)
  • There are some exceptions that I call the "boneheaded" exceptions -- null dereference, index out of range, and so on -- that because they are so easy to avoid and indicate failures so obviously dangerous that they should always be treated as fatal bugs and never handled (unless the "handler" is logging them before shutting down the process.) Don't handle the bug, eliminate the bug.

Finally, you should read my article on this subject.

http://ericlippert.com/2008/09/10/vexing-exceptions/

这篇关于使用guard子句或捕捉异常是否更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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