Best way to check for inner exception?

94,322

Solution 1

Is this what you are looking for?

String innerMessage = (ex.InnerException != null) 
                      ? ex.InnerException.Message
                      : "";

Solution 2

Great answers so far. On a similar, but different note, sometimes there is more than one level of nested exceptions. If you want to get the root exception that was originally thrown, no matter how deep, you might try this:

public static class ExceptionExtensions
{
    public static Exception GetOriginalException(this Exception ex)
    {
        if (ex.InnerException == null) return ex;

        return ex.InnerException.GetOriginalException();
    }
}

And in use:

repEvent.InnerException = ex.GetOriginalException();

Solution 3

That's funny, I can't find anything wrong with Exception.GetBaseException()?

repEvent.InnerException = ex.GetBaseException().Message;

Solution 4

The simplest solution is to use a basic conditional expression:

repEvent.InnerException = ex.InnerException == null ? 
    null : ex.InnerException.Message;

Solution 5

Why so much recursion in these answers?

public static class ExceptionExtensions
{
    public static Exception GetOriginalException(this Exception ex)
    {
        while(ex.InnerException != null)ex = ex.InnerException;
        return ex;
    }
}

Seems like a much more straight forward way to implement this.

Share:
94,322
JL.
Author by

JL.

Developer, Designer , Coder

Updated on July 05, 2022

Comments

  • JL.
    JL. almost 2 years

    I know sometimes innerException is null

    So the following might fail:

     repEvent.InnerException = ex.InnerException.Message; 
    

    Is there a quick ternary way to check if innerException is null or not?

  • Noldorin
    Noldorin over 14 years
    Also, is it just me, or would it look a bit cleaner if the arguments were flipped and the != changed to ==.
  • Andrew Hare
    Andrew Hare over 14 years
    @Noldorin - Sorry dude, I answered this and didn't check to see if I was first! @JL - Noldorin was the first out of the chute with the correct answer, please transfer the accepted answer to him.
  • JL.
    JL. over 14 years
    No problem at all, just that Andrew's code returned a string.
  • Steven Sudit
    Steven Sudit over 14 years
    I'm all for digging down to the oldest exception, but there's really no reason to recurse here. Just loop while inner exception is not null.
  • JL.
    JL. over 14 years
    Am I missing something here or is ex.GetOriginalException() for innerException not top level ex?
  • Noldorin
    Noldorin over 14 years
    @Andrew: Heh, no need to apologise. :) I'm not one to be upset over the issue of a trivial matter, I was just curious as to JL's reason mainly.
  • Noldorin
    Noldorin over 14 years
    @JL: Actually, mind returns a string too. I just assumed from the code that you were calling the string property InnerException (just be confusing?). Never mind though. @Andrew: Thanks. And though I don't at all mind, +1 to yours for the courtesy.
  • tster
    tster over 14 years
    Is recursion evil or something?
  • JL.
    JL. over 14 years
    @Nordorin, Ah I see where the issue comes in, I've gone string because exceptions don't serialize well (if they do at all).
  • jrista
    jrista over 14 years
    I'm not sure what your asking. GetOriginalException will return the original exception that initiated the whole exception chain, regardless of whether there is only one exception (no InnerException at all), or many levels of InnerExceptions.
  • jrista
    jrista over 14 years
    @JL: Exceptions that come with the .NET framework serialize fine, as all of them have a deserialization constructor. Custom exceptions may not serialize properly, but it is easy enough to add a deserialization constructor and override GetObjectData. Third-party extensions could be made serializable with a serialization surrogate.
  • Jan Remunda
    Jan Remunda over 14 years
    E.g. in Entity Framework are usefully exceptions deep inside.
  • Steven Sudit
    Steven Sudit over 14 years
    Recursion isn't evil, but it can be expensive, so if you don't need it, don't use it. In the case of inner exceptions, you have no need to keep pushing the current state onto a stack so that you can continue where you left off, so why use recursion and pay this price? There are also cases where recursion is much, much slower than regular iteration, such as calculating the Fib series.
  • IDIR Samir
    IDIR Samir almost 13 years
    Sweet! I added this as an extension method to be available project-wide
  • Blake Mumford
    Blake Mumford almost 12 years
    Thanks, this helped me find the InnerException of an exception thrown by EntityFramework.
  • Antony
    Antony over 11 years
    I am not sure which version of .Net Framework provides GetOriginalException, but all I can see is GetBaseException(). Is that the same?
  • Justin T Conroy
    Justin T Conroy over 11 years
    He's saying you should implement your own method called GetOriginalException. But yes, it would seem GetBaseException() does the same thing.
  • armadillo.mx
    armadillo.mx over 11 years
    Great!, with this you don't have to do a custom method to navigate through all nested exceptions.
  • krystan honour
    krystan honour almost 11 years
    Works but not for multiple nested exceptions
  • dan-gph
    dan-gph over 7 years
    @StevenSudit, recursion cannot possibly be expensive here. There is no way in the world that he could blow the stack. The difference between the recursive and and iterative versions would be undetectable. The only thing worth worrying about would be which one is easier to understand.
  • dakab
    dakab about 7 years
    +1 𝑓𝑜𝑟 null-conditional and null-coalescing operators. The usage of (ex.InnerException?.Message??"") is convenient, readable and secure.
  • Ashwin
    Ashwin almost 7 years
    The best part with above code is, you no need to worry about null pointer exception i.e checking null before using it(explicitly).
  • Dan Chase
    Dan Chase about 6 years
    I just had an example where I tried to use GetBaseException for a Task<String> for HttpClient, and it continued to just return a higher-level exception. When I implemented this solution, it returned the "Machine actively refused.." message that I was looking for. Great work Jrista!
  • Dan Chase
    Dan Chase about 6 years
    I just had an example where I tried to use GetBaseException for a Task<String> for HttpClient, and it continued to just return a higher-level exception. When I implemented Jrista's solution, it returned the "Machine actively refused.." message that I was looking for.
  • Zimano
    Zimano almost 5 years
    I use the while (ex.InnerException != null) method often and find it very helpful. It can become incredibly verbose at times, however.
  • Thameem
    Thameem over 4 years
    why isn't this answer yet accepted as the correct answer?
  • pushkin
    pushkin about 4 years
    @Thameem There seems to be cases where this doesn't work (e.g. what Dan Chase said above). I'm having a similar problem
  • pushkin
    pushkin about 4 years
    @DanChase This is because AggregationException is overriding GetBaseException. See here and here