其中内置的.NET异常,我可以从我的申请扔?我的、异常、NET

2023-09-04 01:29:13 作者:奈何无明月

如果我需要从我的应用程序,它的内置.NET异常类我可以用抛出一个异常?他们都是公平的游戏?我应该在什么时候得到我自己的?

If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?

推荐答案

请参阅创建和引发异常的。

在投掷内置例外,它说:

On throwing built-in exceptions, it says:

不要从你自己的源$ C ​​$ C抛出System.Exception的,System.SystemException,System.NullReferenceException或System.IndexOutOfRangeException故意。

Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.

不要扔一般例外

如果你把一个一般异常类型,如异常或SystemException的库或框架,它迫使消费者捕获所有异常,包括未知异常,他们不知道如何处理。

If you throw a general exception type, such as Exception or SystemException in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle.

相反,无论是抛出已存在的框架更派生类型,或者创建自己的类型,它源于例外。

Instead, either throw a more derived type that already exists in the framework, or create your own type that derives from Exception."

这博客条目也有一些有用的指导方针。

This blog entry also has some useful guidelines.

此外,FxCop的code分析定义的不抛出异常为的此处描述。它建议:

Also, FxCop code analysis defines a list of "do not raise exceptions" as described here. It recommends:

下面的异常类型过于笼统,以提供足够的信息给用户:

The following exception types are too general to provide sufficient information to the user:    System.Exception的    System.ApplicationException    System.SystemException    System.Exception System.ApplicationException System.SystemException

下面的异常类型被保留,应该由公共语言运行时只抛出:

The following exception types are reserved and should be thrown only by the common language runtime:

   System.ExecutionEngineException    System.IndexOutOfRangeException    System.NullReferenceException   的System.OutOfMemoryException    System.ExecutionEngineException System.IndexOutOfRangeException System.NullReferenceException System.OutOfMemoryException

所以理论上你可以提出任何其他的框架异常类型,为您提供清晰的了解异常的意图所描述的微软(参见MSDN文档)。

So in theory you can raise any other framework exception type, providing you clearly understand the intent of the exception as described by Microsoft (see MSDN documentation).

请注意,这些都是准则和其他一些人也表示,目前各地System.IndexOutOfRangeException是一个有争议(即不少开发商抛出此异常)。

Note, these are "guidelines" and as some others have said, there is debate around System.IndexOutOfRangeException (ie many developers throw this exception).