如果我需要从我的应用程序中抛出异常,我可以使用哪些内置的 .NET 异常类?他们都是公平的游戏吗?我什么时候应该自己导出?
最佳答案
参见 Creating and Throwing Exceptions .
在抛出内置异常时,它说:
Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.
和
Do Not Throw General Exceptions
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."
这blog entry还有一些有用的指南。
此外,FxCop 代码分析将“不引发异常”列表定义为 described here .它建议:
The following exception types are too general to provide sufficient information to the user:
- 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
因此理论上您可以引发任何其他框架异常类型,前提是您清楚地了解 Microsoft 描述的异常的意图(请参阅 MSDN 文档)。
请注意,这些是“准则”,正如其他一些人所说,围绕 System.IndexOutOfRangeException(即许多开发人员抛出此异常)存在争议。
关于c# - 我可以从我的应用程序中抛出哪些内置 .NET 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/218150/