views:

136

answers:

3

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?

A: 

In a word, yes. I cannot think of any significantly better or different way of doing it. Unless you wanted to add it as an extension method instead, but it's really six of one, half-a-dozen of the other.

Quick Joe Smith
+2  A: 

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());
}
AdaTheDev
+1, I liked the other answer better, so that's why I accepted it.
Vinko Vrsalovic
Fair enough, can't argue with that :) Just thought I'd give some example code/test harness demonstrating it in action.
AdaTheDev
+5  A: 

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

public static Exception getInnermostException(Exception e) { 
    return e.GetBaseException(); 
}
daft
Thanks, I need to read more API docs before asking :)
Vinko Vrsalovic