Why can't I catch a generic exception in C#?

后端 未结 3 1452
夕颜
夕颜 2020-12-01 01:13

I was doing some unit testing on code that could throw a number of exceptions depending on the inputs. So I tried something like the below code: (simplified for the example)

3条回答
  •  星月不相逢
    2020-12-01 01:59

    It would seem that the most specific type of the exception, when given the choice between T and Exception, is exception, and so that handler is invoked.

    I just tried this (you can't do it in C# or VB, but I edited the IL), and changed the second catch clause to catch Object Ex rather than Exception Ex, and in that case, the first handler got hit.

    Edit

    As others have pointed out, it's more to do with running it in the debugger than the specific type

提交回复
热议问题