We ran into a weird issue at work today. Take a look at the following code:
public class MyException : Exception { }
[TestFixture]
public class TestFixture
{
[Test]
public void Test()
{
var exception = GetThrownException<MyException>(() => { throw new MyException(); });
Assert.IsNotNull(exception);
}
private T GetThrownException<T>(Action action)
where T : Exception
{
try
{
action();
}
catch (T exception)
{
return exception;
}
return null;
}
}
If you simply run that test, without debugging, it works (both with Testdriven.NET and Resharper). If you run it with a debugger, it fails with the following message:
ExceptionWeirdness.MyException: Exception of type 'ExceptionWeirdness.MyException' was thrown.
Pretty weird huh?
Let's change the code of the GetThrownException method to this:
private T GetThrownException<T>(Action action)
where T : Exception
{
try
{
action();
}
catch (T exception)
{
return exception;
}
catch (Exception e)
{
return (T)e;
}
return null;
}
Now the test works all the time, even with the debugger attached.
Weird huh? At first i wondered if it was somehow NUnit related... but then i tried running this program:
public class MyException : Exception { }
class Program
{
static void Main(string[] args)
{
var exception = GetThrownException<MyException>(() => { throw new MyException(); });
}
private static T GetThrownException<T>(Action action)
where T : Exception
{
try
{
action();
}
catch (T exception)
{
return exception;
}
return null;
}
}
Run it without the debugger, and it works. Run it with the debugger and it fails.
This is using .NET 3.5 SP1.
I don't understand why it behaves like this... it should work all the time right? I am overdue for my weekly brain-fart so i might be missing something really stupid though.
Either way, the first person to explain this behavior gets awarded with the "Davy Brion's Hero Of The Week" title ![]()
Oh, and this was in a clean solution... so there's no duplicate MyException types or anything like that.
Pingback: Exceptional exception handling - KoenV
Pingback: Reflective Perspective - Chris Alcock » The Morning Brew #197
Pingback: Dew Drop - October 9, 2008 | Alvin Ashcraft's Morning Dew