出于好奇,我想看看异常类有什么特别之处,允许它与关键字 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.Exception
、System.ValueType
、System.Delegate
都是 C# 中与语言关键字和 CLR 紧密绑定(bind)的特殊类型,因此您不能只实现接管其角色的类也就不足为奇了。
关于c# - 为什么抛出或捕获的类型必须派生自 System.Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12613805/