在C#中,我不应该使用任何内置的异常吗? [英] In C#, are there any built-in exceptions I shouldn't use?

查看:151
本文介绍了在C#中,我不应该使用任何内置的异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET Framework中是否定义了我不应该在自己的代码中抛出的异常,或者这是一种不好的做法?我应该自己写吗?

Are there any Exceptions defined in the .NET Framework that I shouldn't throw in my own code, or that it is bad practice to? Should I write my own?

推荐答案

您不应抛出由于用户错误而由CLR自动抛出的任何异常。例如

You shouldn't throw any exception that is automatically thrown by the CLR due to user errors. For instance


  • StackOverflowException

  • NullReferenceException

  • AccessViolationException

  • 等...

  • StackOverflowException
  • NullReferenceException
  • AccessViolationException
  • etc ...

原因是这样做会给打电话给您的人造成混乱API。用户应该能够区分API主动抛出的异常和非主动抛出(CLR抛出)的异常。

The reason being is to do so creates confusion for people calling your API. Users should be able to distinguish between actively thrown exceptions by an API and exceptions that are not actively thrown (thrown by CLR).

原因是主动抛出的异常通常表示API中的已知状态。如果我调用一个API并引发ArgumentException,则可以合理地期望给定对象处于良好状态。它认识到潜在的不利局面,并积极予以解决。另一方面,如果它抛出NullRefrenceException,则表明该API遇到未知错误,并且现在处于不可靠状态。

The reason is that at actively thrown exception generally represents a known state in an API. If I call an API and it throwns an ArgumentException, I have a reasonable expectation that the given object is in a good state. It recognized a potentially bad situation and actively accounted for it. On the other hand if it throwns a NullRefrenceException, that is an indication that the API encountered an unknown error and is now in an unreliable state.

另一个较小的原因是,这些异常在被用户代码而不是CLR抛出时表现不同。例如,如果被用户代码抛出,则有可能捕获StackOverflowException,但如果由CLR抛出,则不会捕获。

Another lesser reason is that these exceptions behave differently when thrown by user code as opposed to the CLR. For instance it's possible to catch a StackOverflowException if thrown by user code, but not if it's thrown by the CLR.

  • http://blogs.msdn.com/jaredpar/archive/2008/10/22/when-can-you-catch-a-stackoverflowexception.aspx

编辑响应Michael的评论

EDIT Responding to Michael's comment

您也不应该直接抛出Exception,ApplicationException或SystemException。这些异常类型过于笼统,无法为调用您的API的代码提供有意义的信息。可以,您可以在message参数中添加一个非常描述性的消息。但是,根据消息捕获异常并非直截了当或无法维护。最好根据类型来捕获它。

You also should not throw Exception, ApplicationException or SystemException directly. These exceptions types are too general to provide meaningful information to the code which calls your API. True you can put a very descriptive message into the message parameter. But it's not straight forward or maintainable to catch an exception based on a message. It's much better to catch it based on the type.

关于此主题的FxCop规则: http://msdn.microsoft.com/zh-cn/library/ms182338(VS.80).aspx

FxCop rule on this subject: http://msdn.microsoft.com/en-us/library/ms182338(VS.80).aspx

这篇关于在C#中,我不应该使用任何内置的异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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