Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 825
Daniel T. Avatar asked Oct 06 '10 20:10

Daniel T.


People also ask

How do I find an inner exception?

When you're debugging and you get an exception, always, always, always click on the View Details link to open the View Details dialog. If the message in the dialog isn't expanded, expand it, then scan down to the Inner Exception entry.

What is inner exception give example?

Inner Exception Example in C#:Let us say we have an exception inside a try block that is throwing DivideByZeroException and the catch block catches that exception and then tries to write that exception to a file. However, if the file path is not found, then the catch block is also going to throw FileNotFoundException.

Can inner exception be null?

Property Value The InnerException property returns the same value as was passed into the Exception(String, Exception) constructor, or null if the inner exception value was not supplied to the constructor.

Does exception ToString include inner exception?

The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.


2 Answers

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.

like image 153
Draco Ater Avatar answered Oct 03 '22 10:10

Draco Ater


I believe Exception.GetBaseException() does the same thing as these solutions.

Caveat: From various comments we've figured out it doesn't always literally do the same thing, and in some cases the recursive/iterating solution will get you further. It is usually the innermost exception, which is disappointingly inconsistent, thanks to certain types of Exceptions that override the default. However if you catch specific types of exceptions and make reasonably sure they're not oddballs (like AggregateException) then I would expect it gets the legitimate innermost/earliest exception.

like image 26
Josh Sutterfield Avatar answered Oct 03 '22 12:10

Josh Sutterfield