Catch/Modify (Message)/Rethrow Exception of same type

What you are trying to do here is not as easy as it seems and there are lots of pitfalls to consider.

Remember, that Convert.ChangeType() will convert one type to another (assuming such a path exists, like converting a string to an int for example). Most exceptions wont do this (Why would they?)

IN order to pull this off, you would have to examine the exception type at runtime with the GetType() method and locate a constructor that has requirements you can satisfy and invoke it. Be careful here, since you don't have control over how all exceptions are defined there is no guarantee you will have access to "standard" constructors.

That being said, if you feel like being a rule breaker you could do something like this...

void Main()
{
    try
    {   
        throw new Exception("Bar");
    }
    catch(Exception ex)
    {
        //I spit on the rules and change the message anyway
        ex.GetType().GetField("_message", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ex, "Foo");
        throw ex;
    }
}

You could do this to dynamically call the constructor of the exception type:

object newEx = Activator.CreateInstance(ex.GetType(), new object[] { msg });

Your original code would fail at runtime, because for Convert.ChangeType towork, the exception type would have to implement IConvertible and support conversion to the other exception type, which i doubt.


May be it's a bit late, but would this work for you?

catch (Exception ex)
{
    throw new Exception("New message", ex);
}