I need for exceptions thrown within a timed event to be bubbled up and handled outside of the event handler context. I had read that System.Threading.Timers
would be able to do that, provided that, as outlined in the answer to this question, the exception is caught in the callback method and a mechanism is used to re-throw it. Using this example as a guide, I created an event handler which throws and a method which should catch and re-throw the exception using an IProgress
object:
void ThrowerThreaded() {
var progress = new Progress<Exception>((ex) => {
throw ex;
});
Timer timer = new Timer(x => onTimerElapsedThrow2(progress), null, 10, -1);
Thread.Sleep(1000);
}
void onTimerElapsedThrow2(IProgress<Exception> progress) {
try {
throw new Exception();
} catch (Exception ex) {
progress.Report(ex);
}
}
I then wrote a unit test to see if the exception would bubble up:
[TestMethod]
public void TestThreadedTimerThrows() {
Assert.ThrowsException<Exception>(ThrowerThreaded);
}
The test case fails indicating no exception was thrown. If I debug the test case, I can clearly see that the exception is caught and re-thrown in ThrowerThreaded()
however the method still continues and exists normally. Why is the exception still being suppressed?