I’m trying to implement exception handling in my program. I’ve done the simple thing of putting try/catch blocks around the obvious places and they work fine. Now I’m trying to put a try/catch block around the whole program to catch exceptions anywhere. Since the vast majority of my program runs in a while loop, it isn’t all that hard. Here’s a pseudo code version of what I’m doing.
missionRun = true;
while (missionRun)
{
try
{
callThisMethod();
callThatMethod();
callTheOtherMethod();
CPFUtilities.divideByZero;
}
catch (Exception currentException)
{
sbTemp.Clear();
sbTemp.Append("*** Exception in State Machine loop: ");
sbTemp.Append(currentException.HResultToString());
EngrLogger.writeComment(UTF8Encoding.UTF8.GetBytes(EngrLogger.getPrefix(sbTemp).ToString()));
CPFStateTimer.Change(configFile.EATimeout, configFile.timeoutDefaultPeriod);
CPFState = CPFStates.EmergencyAscend;
}
}
The .divideByZero method is the test method I use to force an exception. I can put the .divideByZero where shown and the catch block works fine, I can put it in one of the methods called in the main loop and the catch block works fine, I can put it in a method that is called by a method in the main loop and the catch block works fines. However, if I put the .divideByZero method in an event handler, an exception is thrown that isn’t caught by my catch block and my program hangs.
Can anyone explain why my catch block seems to catch any exception that pops up in a method but not an exception that pops up in an event handler? More importantly, is there a better solution than putting a try/catch block around every event handler in my program?
Thanks