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

Daniel T. picture Daniel T. · Oct 6, 2010 · Viewed 42.5k times · Source

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.

Answer

Draco Ater picture Draco Ater · Oct 6, 2010

Oneliner :)

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

Obviously, you can't make it any simpler.

As said in this answer by Glenn McElhoe, it's the only reliable way.