Click here to Skip to main content
15,880,972 members
Articles / Programming Languages / C#
Tip/Trick

Find your inner exception

Rate me:
Please Sign up or sign in to vote.
4.83/5 (6 votes)
12 Sep 2013CPOL 43.9K   9   13
One approach to find a specific exception type inside the containing exception

Introduction

We have some code that uses CSLA, and in the process of manipulating the database, an exception is being thrown that we handle via a custom exception. In some cases, CSLA leaves the thrown exception alone, but in others, it decorates the exceptions message something like this: "DataPortal_Fetch.Error blah blah blah:OUR INTENDED MESSAGE HERE: stack trace info". After spending 30 minutes trying (and failing) to finger out where this decoration was happening, I came up with the following solution.


The Code

I create this extension method for the Exception class:

C#
public static class ExceptionExtension
{
    public static T FindInnerException<T>(this Exception ex) where T : Exception
    {
        if (!ex.GetType().Equals(typeof(T)))
        {
            Exception inner = ex.InnerException;
            if (inner == null)
            {
                return null;
            }
            else
            {
                if (inner.GetType().Equals(typeof(T)))
                {
                    return (T)inner;
                }
                else
                {
                    return inner.FindInnerException<T>();
                }
            }
        }
        else
        {
            return (T)ex;
        }
    }
}

It's pretty simple really. The code is looking for the first exception in the chain for the specified exception type. If the end of the chain is reached before finding the desired type, the method returns null. If it finds the desired type, it returns the exception it found.

NOTE: Fred Flams posted a comment with a modification that makes the code a little more versatile. Make sure you check it out. What about chain of inheritance[^]

Usage

C#
try
{
    // do something that could throw your custom exception
}
catch (Exception ex)
{
    MyCustomException myEx = ex.FindInnerException<MyCustomException>();
    if (myEx != null)
    {
        // do something with the exception
    }
}

History

  • Original Creation: 09/11/2013

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
QuestionAnother proposition Pin
Octopod6-Feb-23 0:37
Octopod6-Feb-23 0:37 
QuestionWhat is the error? Pin
Ammar Al-hamdabni15-Sep-13 5:09
Ammar Al-hamdabni15-Sep-13 5:09 
AnswerRe: What is the error? Pin
PIEBALDconsult15-Sep-13 5:54
mvePIEBALDconsult15-Sep-13 5:54 
GeneralRe: What is the error? Pin
Ammar Al-hamdabni15-Sep-13 7:11
Ammar Al-hamdabni15-Sep-13 7:11 
AnswerRe: What is the error? Pin
#realJSOP16-Sep-13 15:26
mve#realJSOP16-Sep-13 15:26 
SuggestionI like it ;) Pin
Paw Jershauge12-Sep-13 22:19
Paw Jershauge12-Sep-13 22:19 
GeneralMy vote of 5 Pin
johannesnestler12-Sep-13 4:57
johannesnestler12-Sep-13 4:57 
QuestionWhat about chain of inheritance Pin
Fred Flams12-Sep-13 1:45
Fred Flams12-Sep-13 1:45 
Hello,

You search only for the exact matching type, I would have included a search for subclasses to.
If you have say a SQLException and a SQLBufferException that inherits from SQLException. Using your search I need to know exactly what type of exception I'm looking for, so I will search for SQLBufferException. Now someone changes my database and I'm no longer receiving a SQLBufferException but a SQLOverflowException instead, I have to go back to my code and change the search filtre, compile and deploy/ship again. Using your filter as is I can't search for SQLException because I won't find it (only inherited types). I would be stuck and obliged to go back to code everytime the inner exception changes.

What I'm proposing is a very simple change in your logic:
C#
public static T FindInnerException<T>(this Exception ex) where T : Exception
{
    var exType = ex.GetType();
    var searchedType = typeof(T);

    if (!exType.Equals(searchedType) && !exType.IsSubclassOf(searchedType))
    {
        Exception inner = ex.InnerException;
        if (inner == null)
        {
            return null;
        }
        else
        {
            var innerType = inner.GetType();

            if (innerType.Equals(searchedType) || innerType.IsSubclassOf(searchedType))
            {
                return (T)inner;
            }
            else
            {
                return inner.FindInnerException<T>();
            }
        }
    }
    else
    {
        return (T)ex;
    }
}


And voila, you can search for the generic SQLException in you chain of InnerExceptions.
My 4 by the way

Fred
AnswerRe: What about chain of inheritance Pin
johannesnestler12-Sep-13 4:56
johannesnestler12-Sep-13 4:56 
GeneralRe: What about chain of inheritance Pin
Fred Flams13-Sep-13 1:39
Fred Flams13-Sep-13 1:39 
GeneralRe: What about chain of inheritance Pin
Richard Deeming18-Sep-13 5:06
mveRichard Deeming18-Sep-13 5:06 
AnswerRe: What about chain of inheritance Pin
#realJSOP12-Sep-13 7:18
mve#realJSOP12-Sep-13 7:18 
GeneralRe: What about chain of inheritance Pin
Fred Flams13-Sep-13 1:44
Fred Flams13-Sep-13 1:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.