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

前端 未结 6 1016
独厮守ぢ
独厮守ぢ 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:15

    One reason why every exception needs to have a universal base class is so you can catch every type of exception in a single catch block.

    If I have this:

    try
    {
        ...
    }
    catch(Exception ex)
    {
        // Handle somehow
    }
    

    That will catch ALL exceptions, and will allow me to display what it is (by using ex.Message).

    If you could throw anything, then how would you have a catch that would catch everything and still give you access to the object thrown?

    You could have this, which will catch absolutely everything:

    try
    {
        ...
    }
    catch
    {
        // Handle somehow
    }
    

    But you have 'lost' the thing that was thrown.

提交回复
热议问题