I'm working with some classes which, when throwing, have a relatively deep InnerException tree. I'd like to log and act upon the innermost exception which is the one having the real reason for the problem.
I'm currently using something similar to
public static Exception getInnermostException(Exception e) {
while (e.InnerException != null) {
e = e.InnerException;
}
return e;
}
Is this the proper way to handle Exception trees?
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.
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.
An object that describes the error that caused the current exception. 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.
Absolutely - you can retrieve the inner exception (the "cause") using Throwable. getCause() . To create an exception with a cause, simply pass it into the constructor. (Most exceptions have a constructor accepting a cause, where it makes sense.)
I think you can get the innermost exception using the following code:
public static Exception getInnermostException(Exception e) {
return e.GetBaseException();
}
You could use the GetBaseException method. Very quick example:
try
{
try
{
throw new ArgumentException("Innermost exception");
}
catch (Exception ex)
{
throw new Exception("Wrapper 1",ex);
}
}
catch (Exception ex)
{
// Writes out the ArgumentException details
Console.WriteLine(ex.GetBaseException().ToString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With