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

Viewed 47472

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 inner exception. I can do this in a while loop:

while (e.InnerException != null)
{
    e = e.InnerException;
}

But I was wondering if there was some one-liner I could use to do this instead.

12 Answers

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.

I ran into this and wanted to be able to list all of the exception messages from the exception "stack". So, I came up with this.

public static string GetExceptionMessages(Exception ex)
{
    if (ex.InnerException is null)
        return ex.Message;
    else return $"{ex.Message}\n{GetExceptionMessages(ex.InnerException)}";
}
Related