Find the inner-most exception without using a while loop?

前端 未结 12 788
南旧
南旧 2020-12-12 18:54

When C# throws an exception, it can have an inner exception. What I want to do is get the inner-most exception, or in other words, the leaf exception that doesn\'t have an i

12条回答
  •  不知归路
    2020-12-12 19:35

    Another way you could do it is by calling GetBaseException() twice:

    Exception innermostException = e.GetBaseException().GetBaseException();
    

    This works because if it is an AggregateException, the first call gets you to the innermost non-AggregateException then the second call gets you to the innermost exception of that exception. If the first exception is not an AggregateException, then the second call just returns the same exception.

提交回复
热议问题