Click here to Skip to main content
Click here to Skip to main content

Tagged as

Cloning an Exception (kinda sorta)

, 10 Apr 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Using Reflection to instantiate an Exception of a given type
Sometimes, when you catch an Exception, you just want to add some information and re-throw. One way to do that is to add items to the Exception's Data collection, but I don't think many developers do that (I don't).
 
The other way to do that is to instantiate and throw a new Exception. When doing this, you should include the original Exception as an InnerException -- but all too often developers don't Sigh | :sigh: .
 
One good thing about this technique is that you can throw a different (hopefully more-descriptive) type of Exception. Buuut... all too often, the developer simply instantiates a base Exception, which hinders the ability to catch and handle the Exception properly.
 
And, when you combine the poor practice of replacing a derived Exception with a base Exception with not including the original Exception as an InnerException, you create a situation where tracking down and handling an Exception is rather difficult (yes, I was put in this situation this week).
 
So, what can a developer do to throw a proper Exception? Obviously, you can catch different types of Exception and throw based on that. But that may not be the best general solution.
 
As I thought about this situation this week, I saw that a little bit of Reflection would allow me to instantiate an Exception of the same type that was caught (in most cases), so I wrote the following:
 
namespace PIEBALD.Lib.LibExc.Clone
{
    public static partial class LibExc
    {
        private static readonly System.Collections.Generic.Dictionary
            <System.Type,System.Reflection.ConstructorInfo> con ;
 
        private static readonly System.Type[] sig ;
 
        static LibExc
        (
        )
        {
            con = new System.Collections.Generic.Dictionary
                <System.Type,System.Reflection.ConstructorInfo>() ;
 
            sig = new System.Type[]
            {
                typeof(string)
            ,
                typeof(System.Exception)
            } ;
 
            return ;
        }
 
        public static System.Exception
        Clone
        (
            this System.Exception Source
        ,
            string                Message
        ,
            params object[]       Params
        )
        {
            System.Type typ = Source.GetType() ;
 
            if ( !con.ContainsKey ( typ ) )
            {
                System.Reflection.ConstructorInfo temp = typ.GetConstructor
                (
                    System.Reflection.BindingFlags.Public
                    |
                    System.Reflection.BindingFlags.Instance
                ,
                    null
                ,
                    sig
                ,
                    null
                ) ;
 
                if ( temp == null )
                {
                    throw ( new System.Exception ( "No constructor found for type " + typ.Name , Source ) ) ;
                }
 
                con [ typ ] = temp ;
            }
 
            return ( (System.Exception) con [ typ ].Invoke
            (
                new object[]
                {
                    System.String.Format ( Message , Params )
                ,
                    Source
                }
            ) ) ;
        }
    }
}
 
I called it Clone even though it's not a true clone operation, but I think it conveys the basic idea of what it does.
 
Also, not all Exception types have public constructors that take a string and an Exception (System.Data.SqlClient.SqlException
for instance). In these cases, the above code will throw an Exception, but that may not be the best solution. I just haven't yet decided what I want to do: I could have a fall-back Exception type, I could allow the developer to specify a fall-back Exception type, or I can search the parent types until a suitable type is found. Please post opinions of what you think should be done.
 
I also have a VB.NET version, but it's uuugly! Big Grin | :-D

License

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

Share

About the Author

PIEBALDconsult
Software Developer (Senior)
United States United States
BSCS 1992 Wentworth Institute of Technology
 
Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.
 
OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB
 
---------------
 
"If you need help knowing what to think, let me know and I'll tell you." -- Jeffrey Snover [MSFT]
 
"Typing is no substitute for thinking." -- R.W. Hamming
 
"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup
 
ZagNut’s Law: Arrogance is inversely proportional to ability.
 
"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon
 
"linq'ish" sounds like "inept" in German -- Andreas Gieriet
 
"Things would be different if I ran the zoo." -- Dr. Seuss
 
"Wrong is evil, and it must be defeated." – Jeff Ello
 
"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw
 
“It’s always easier to do it the hard way.” -- Blackhart

“If Unix wasn’t so bad that you can’t give it away, Bill Gates would never have succeeded in selling Windows.” -- Blackhart

"Omit needless local variables." -- Strunk... had he taught programming
 

 
"We learn more from our mistakes than we do from getting it right the first time."
 
My first rule of debugging: "If you get a different error message, you're making progress."
 
My golden rule of database management: "Do not unto others' databases as you would not have done unto yours."
 
My general rule of software development: "Design should be top-down, but implementation should be bottom-up."

Comments and Discussions

 
GeneralReason for my vote of 5 Useful technique, especially in algo... PinmemberDrABELL9-Apr-11 13:40 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 10 Apr 2011
Article Copyright 2011 by PIEBALDconsult
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid