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

推荐答案

请参见Creating 和 Throwing Exceptions.

在抛出内置异常时,它说:

不要扔系统.例外,系统.系统例外,系统.NullReferenceException或System.IndexOutOfRangeException故意从您自己的源代码中删除.

不要抛出一般异常

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 h和le.

相反,要么抛出框架中已经存在的更派生的类型,要么创建自己的从Exception派生的类型."

blog entry条也有一些有用的指导方针.

此外,FxCop代码分析将"不引发异常"列表定义为described here.它建议:

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

  • System.Exception
  • 系统应用程序异常
  • 系统系统例外

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

  • 系统ExecutionEngineeException
  • 系统IndexOutOfRangeException
  • 系统NullReferenceException
  • 系统OutOfMemoryException

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

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

.net相关问答推荐

.NET Blazor-使用子组件中的处理程序方法进行双向数据绑定

.NET restore/build在使用组织包的Github Action工作流中调用时获得401

如何使用.NET8MapIdentityApi设置OpenApi操作ID

EGC / 文本元素上的 .NET String.Split

在 .NET 中使用 AES 解密时缺少后半字节

无法加载文件或程序集 Microsoft.Extensions.DependencyInjection.Abstractions,版本 = 1.1.0.0

从 switch 块中跳出 foreach 循环

extern 在 C# 中是如何工作的?

SubscribeOn 和 ObserveOn 有什么区别

C# 属性实际上是方法吗?

如何退出所有正在运行的线程?

将接收到的对象转换为 List 或 IEnumerable

仅使用 XAML 绘制纯色三角形

从 OpenFileDialog 路径/文件名中提取路径

为什么 double.NaN 不等于自身?

如何以编程方式删除 WebClient 中的 2 个连接限制

Guid.Parse() 或 new Guid() - 有什么区别?

System.Array.CopyTo() 和 System.Array.Clone() 之间的区别

如何判断枚举是否包含数字?

通过反射获取公共静态字段的值