是否可以捕获异常,什么也不做? [英] Is it ever okay to catch an exception and do nothing?

查看:392
本文介绍了是否可以捕获异常,什么也不做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  try 
{

CallMethod()

}
catch {}

根据我的经验,我通常不会这样做。



但是如果我有一个功能说,使用第三方COM程序集,偶尔失败,它实际上不够重要,记录它,因为我会打电话



如果没有,我还有什么选择?



例如,下面的代码可以用来解决这个问题:class =h2_lin>解决方案

你的问题也会捕获OutOfMemoryException,StackOverflowException,ExecutionEngineException,AccessViolationException和ThreadAbortException(虽然后者将在catch块结束时重新抛出)。它甚至会捕获不从System.Exception派生的对象(很少,但可能在托管C ++和JavaScript ...在CLR中,任何对象可以抛出,但C#限制你到异常派生类型)。



如果在你的例子中,你使用的第三方COM对象偶尔失败,你不在乎这些失败,你应该抓住(COMException) {},以便其他更严重的错误冒泡,并可以记录和/或修复。



重要的是只捕获那些你可以做某事的异常(在这种情况下,你明确选择不对CallMethod()产生的异常做任何处理,我同意添加一个注释来表示这个设计决定)。通过遵循该指南,您可以防止代码或运行时环境中的其他错误和问题被忽视。


try
{

    CallMethod()

}
catch { }

From my experience, I generally wouldn't do this.

But if I had a piece of functionality that say, uses a 3rd party COM assembly which occasionally fails and it's actually not important enough to log it cause I'll be calling it again in a couple of seconds anyway, is it okay to do this?

If not, what alternative do I have?

解决方案

An empty catch block like the one shown shouldn't be used.

For example, the code in your question would also catch OutOfMemoryException, StackOverflowException, ExecutionEngineException, AccessViolationException and ThreadAbortException (though the latter would be rethrown at the end of the catch block). It would even catch objects that don't derive from System.Exception (rare, but possible in managed C++ and JavaScript...in the CLR, any object can be 'thrown', but C# limits you to Exception-derived types).

If, in your example, you're using a 3rd party COM object that occasionally fails and you don't care about these failure, you should instead catch (COMException) {}, so that other more serious failures 'bubble up' and can be logged and/or fixed.

It's important to catch only those exceptions that you can actually do something about (in this case, you're explicitly choosing to do nothing about exceptions arising from CallMethod(), and I agree that a comment should be added to indicate this design decision). By following that guidance, you're preventing other bugs and problems in either the code or the runtime environment from going unnoticed.

这篇关于是否可以捕获异常,什么也不做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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