c# - 我可以从我的应用程序中抛出哪些内置 .NET 异常?

标签 c# .net exception

如果我需要从我的应用程序中抛出异常,我可以使用哪些内置的 .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/

相关文章:

c# - 当 AutoGenerateColumns = True 时如何重命名 DataGrid 列?

C#/ASP.NET - 从 PDF/DOC 文件获取缩略图

c# - 如何捕获重新抛出的异常?

C#:反射实例化对象会引发转换错误?

c# - 未处理的异常终止执行时退出代码?

php - 如何为fopen()中的错误文件路径在PHPUnit中设置预期的异常?

c# - 为什么我得到 "The given path' 格式不受支持”错误

c# - 删除和选项请求得到 401 未经授权的响应

c# - 如何将 C# 委托(delegate)函数传递给托管 C++ .Dll?

c# - 套接字保持套接字打开,只检查客户端发送的消息