为什么异常是一个类,而不是一个结构体?

4
  • Exception represents a single piece of information.
  • Exceptions are (or should be) by definition rare occurrence in application lifetime so boxing, unboxing and copying are not an issue I think.
  • Exceptions almost always go out of scope from where they were created, so there is a risk of having reference to exception stored somewhere making it good candidate for promotion to next GC generation, while structs are easier to cleanup.
  • Immutable Struct is thread safe.
  • You never want Exception to be null (even compiler or CLR forces this, try doing whats below):

    throw null;
    

    then, you'll get:

    NullReferenceException
    

异常为什么是类,有何特定原因吗?


4
您永远不希望“Exception”为空。可以检查Exception.InnerException是否为空。结构需要在堆栈中分配,但如果发生堆栈溢出,您将分配什么?此外,“结构体可以实现接口,但不能从另一个结构继承”,就像文档所说的那样。 - oleksa
1
很多答案,但一个非常重要的答案是,你不能有结构体的层次结构 - 而且异常的层次结构非常重要,并且对catch工作方式是基本的(即,你从最具体到最一般派生的异常中catch以处理特定情况)。 - Matthew Watson
@oleksa 你说得完全正确。继承是将异常作为类的重要论点。 - Creo
1
同时,内部异常也是不可能的,这将禁止使用原始异常的上下文抛出更高级别的异常。 - Philippe
1个回答

4

两个最重要的事情:

  • 结构体不能被继承,因此您无法在异常中创建任何层次结构
  • 在 StackOverflowException 的情况下,您无法在堆栈上分配内存,需要使用堆

1
我不认为这是原因。我们还有“OutOfMemoryException”。[在出现StackOverflowException时,您无法在堆栈上分配内存,需要使用堆] - Serg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接