How to set the InnerException of custom Exception class from its constructor

Viewed 35339

How can I set the InnerException property of an Exception object, while I'm in the constructor of that object? This boils down to finding and setting the backing field of a property that has no setter.

BTW: I have seen this evain.net - Getting the field backing a property using Reflection but looking for non IL-based solution, if possible.

The constructor of Exception is the place where the Exception type is created, so I cannot call it using the base class constructor MyException() :base(...) etc.

10 Answers

In my situation I used this code:

class Foo 
{
    void Bar(MyException myException = null)
    {
        try
        {
            SomeActions.Invoke();
        }
        catch (Exception ex)
        {
            if (myException != null)
            {
                // Here I regenerate my exception with a new InnerException
                var regenMyException = (MyException)System.Activator.CreateInstance(myException.GetType(), myException.Message, ex);
                throw regenMyException;
            }

            throw new FooBarException("Exception on Foo.Bar()", ex);
        }
    }
}

HTH someone ;).

Extension methods work well.

namespace MyNamespace
{
    public static class ExceptionExtensions
    {
        public static void SetInnerException(this Exception exception, string innerExceptionMessage)
        {
            typeof(Exception)
                .GetField("_innerException", BindingFlags.NonPublic | BindingFlags.Instance)
                .SetValue(exception, new Exception(innerExceptionMessage));
        }
    }
}

Then in your catch block when you want to add the inner exception:

try
{
    throw new Exception("Main Message");
}
catch (Exception ex)
{
    ex.SetInnerException("Inner Message");
    throw;
}
Related