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?

推荐答案

See Creating and Throwing Exceptions.

On throwing built-in exceptions, it says:

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

and

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."

This blog entry also has some useful guidelines.

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

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

  • System.ExecutionEngineException
  • System.IndexOutOfRangeException
  • System.NullReferenceException
  • System.OutOfMemoryException

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).

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

.net相关问答推荐

EF Core IEntityTypeConfigurations:从数据库提取数据后相关对象为空

WinForm Task.Wait :为什么它会阻塞 UI?

在`MAUI`应用中使用Android`MediaPlayer`的`prepare`方法只在发布模式下和在物理设备上崩溃

与 Datagrid 的 SelectedItem 链接时的 WPF RadioButton 绑定问题

使用 PEM 文件创建 DSA 签名

为什么 StyleCop 建议在方法或属性调用前加上this?

每第 N 个字符/数字拆分一个字符串/数字?

ILMerge 最佳实践

C#:内存不足异常

为什么 ?: 会导致转换错误,而 if-else 不会?

如何将 NuGet 与 Visual C# Express 一起使用?

为什么 WCF 中不允许方法重载?

SQLParameter 如何防止 SQL 注入?

在同一解决方案中引用 2 个不同版本的 log4net

如何防止任务的同步延续?

Dispatcher.CurrentDispatcher 与 Application.Current.Dispatcher

我应该如何删除 DbSet 中的所有元素?

将月份 int 转换为月份名称

清除文件内容

如何在 C# 中使用迭代器反向读取文本文件