Why must a type thrown or caught derive from System.Exception

前端 未结 6 1024
独厮守ぢ
独厮守ぢ 2021-02-12 09:44

So just out of curiosity I wanted to see what was special about the exception class that allowed it to be used with the keyword Throw while a standard class is not.

6条回答
  •  面向向阳花
    2021-02-12 10:10

    I think your premise is mistaken. It is possible that an object is thrown that is not derived from System.Exception. You just can't throw it in C# or examine the object in a catch clause. From section 8.10 of the C# spec (v4.0):

    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.

    An example of a general catch:

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

    In particular, this is important when calling unmanaged code.

    Some types always seem to get special treatment in every language. Mostly because they are so fundamental to the system. System.Exception, System.ValueType, System.Delegate are all special types in C# that are tightly bound to language keywords and the CLR, so it is not surprising that you can't just implement classes that take over their roles.

提交回复
热议问题