Getting actual type from an exception thrown in base class

I have a series of classes in my application set up like follows:

abstract class Foo<TYPE> where TYPE : new()
{
    public void Error() 
    {
        List<TYPE> foo = null;
        foo.Add(new TYPE());
    }
}

class Bar : Foo<int>
{

}

When the call to Bar.Error() throws an exception, the stack trace simply reports it as being in Foo'1.Error(). I know exactly why it does that, but I need to know that it was a Bar object actually throwing the error. How can I derive that from the Exception object that gets thrown?

Jon Skeet
people
quotationmark

You can't, just from an exception you don't control. There's no indication in the exception what instance happened to have a method executing when the exception was generated.

I would suggest using a debugger (so that you can break if the exception is thrown) and/or using more diagnostic logging. (For example, log the type of this at the start of the method.)


Original answer, when the method itself directly threw the exception

(Keeping this for posterity - it might be useful to others.)

You could use the Source property, or perhaps the Data property to record the name of the type or the instance. For example:

abstract class Foo<TYPE>
{
    public void Error() 
    {
        throw new Exception("Whoops") { Data = {{ "Instance", this }} };
    }
}

... then use:

catch (Exception e)
{
    var instance = e.Data["instance"];
    // Use the instance
}

This is a pretty odd use, however. It may well be more appropriate to throw your own custom exception type which explicitly knows about the instance that generated it.

people

See more on this question at Stackoverflow