Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to find the innermost exception?

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?

like image 710
Vinko Vrsalovic Avatar asked Jan 18 '10 10:01

Vinko Vrsalovic


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.

What is inner exception details?

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.

How do you throw an inner exception in Java?

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.)


2 Answers

I think you can get the innermost exception using the following code:

public static Exception getInnermostException(Exception e) { 
    return e.GetBaseException(); 
}
like image 112
Henric Avatar answered Oct 13 '22 05:10

Henric


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());
}
like image 26
AdaTheDev Avatar answered Oct 13 '22 06:10

AdaTheDev