Rethrowing Modifies Same Exception Object
Once you read the code, you'll understand what I'm asking. But what I'm
interested in is basically why is this a design decision by the CLR team.
using System;
public class Test
{
static Exception _ex;
public static void Main()
{
try
{
try
{
throw new Exception();
}
catch(Exception ex)
{
_ex = ex; // save the caught exception as-is (maybe for future
diagnostics)
throw ex; // rethrow, changes stack trace
}
}
catch(Exception ex)
{
Console.WriteLine(object.ReferenceEquals(ex, _ex));
// outputs True. the runtime uses the same original object instead
// of creating a new one on rethrow, hence destroying my
diagnostic capabilities
// unless I do a manual copy of the object before saving it.
}
}
}
Note that one possible explanation is that Exception is inheritable, and a
reference type, and therefore the runtime can't guarantee that it knows
how to copy it properly, assuming everything else we already know about
the CLR.
However, that doesn't explain why certain measures weren't taken to indeed
allow the CLR to copy exception objects by itself if/when beneficial.
No comments:
Post a Comment