c# - 为什么抛出或捕获的类型必须派生自 System.Exception

标签 c# .net exception compiler-errors

出于好奇,我想看看异常类有什么特别之处,允许它与关键字 Throw 一起使用,而标准类则不能。

我所发现的是 Exception 类实现了以下内容

public class Exception : System.Object, System.Runtime.Serialization.ISerializable, System.Runtime.InteropServices._Exception
{
}

所以我尝试实现那些相同的接口(interface)并尝试抛出我自己的自定义异常,该异常不是从 System.Exception 派生的,但无济于事。我只是被告知

The type caught or thrown must be derived from System.Exception

那么这有什么具体原因吗?我假设托管语言中的选择很少,似乎是任意的。

最佳答案

我认为你的前提是错误的。有可能抛出不是派生自 System.Exception 的对象。您只是不能将其放入 C# 或检查 catch 子句中的对象。来自 C# 规范 (v4.0) 的第 8.10 节:

Some programming languages may support exceptions that are not representable as an object derived from System.Exception, although such exceptions could never be generated by C# code. A general catch clause may be used to catch such exceptions. Thus, a general catch clause is semantically different from one that specifies the type System.Exception, in that the former may also catch exceptions from other languages.

一般捕获的示例:

try
{
}
catch (Exception) { } // 'specific' catch
catch { } // 'general' catch

尤其是,这在调用非托管代码时很重要。

某些类型似乎总是在每种语言中得到特殊对待。主要是因为它们是系统的基础。 System.ExceptionSystem.ValueTypeSystem.Delegate 都是 C# 中与语言关键字和 CLR 紧密绑定(bind)的特殊类型,因此您不能只实现接管其角色的类也就不足为奇了。

关于c# - 为什么抛出或捕获的类型必须派生自 System.Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12613805/

相关文章:

python - 在 Python 中,将异常记录到文件的最佳方式是什么?

php - Laravel 异常处理程序还会记录请求

C# 在继续之前等待来自所有线程的信号

c# - 区域 - 日期和时间问题

c# - 如何将 json 字符串序列化为表单发布数据

.net - 调用 SAP PI Web 服务时出现 "Not a valid date in accord with the XML format for ABAP"错误

c# - Predicates 或 Actions 是否具有任何其他属性或特性以将它们与 Funcs 区分开来?

.net - 我可以更改 C# WebMethod 中的参数名称吗?

exception - 使用线程池时出现 Hadoop 'Filesystem closed' 异常

c# - 该方法或操作未实现。在 C# 中停止 IIS 网站时