Click here to Skip to main content
13,353,462 members (66,108 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


4 bookmarked
Posted 9 Apr 2011

Cloning an Exception (kinda sorta)

, 10 Apr 2011
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: .

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[]
            } ;

            return ;

        public static System.Exception
            this System.Exception Source
            string                Message
            params object[]       Params
            System.Type typ = Source.GetType() ;

            if ( !con.ContainsKey ( typ ) )
                System.Reflection.ConstructorInfo temp = typ.GetConstructor
                ) ;

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

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! :D


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


About the Author

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, acknowledged pedant and contrarian


"Using fewer technologies is better than using more." -- Rico Mariani

"Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" -- Steve McConnell

"Every time you write a comment, you should grimace and feel the failure of your ability of expression." -- Unknown

"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

"Use vertical and horizontal whitespace generously. Generally, all binary operators except '.' and '->' should be separated from their operands by blanks."

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

You may also be interested in...

Comments and Discussions

GeneralReason for my vote of 5 Useful technique, especially in algo... Pin
DrABELL9-Apr-11 13:40
memberDrABELL9-Apr-11 13:40 
Reason for my vote of 5
Useful technique, especially in algorithm-centric type of applications with multiple nested classes and methods overriding. 5*

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180111.1 | Last Updated 10 Apr 2011
Article Copyright 2011 by PIEBALDconsult
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid