简体   繁体   中英

Catching exceptions thrown when invoking Application.DoEvents()

Im new to .Net and I'm wondering why this code still raises unhandled exception.

try
{
    Application.DoEvents();
}
catch
{
}

Does anyone have any idea? This code is invoked inside an event handler. It throws NullReferenceException. The funny thing is when I try to put a breakpoint right before this code, the exception is not being thrown. The exception occurs only when I let the code run continuously.

Not all exceptions are catchable. You didn't tell us what exception you are seeing, but note that StackOverflowException and ExecutionEngineException can not ever ever ever be caught. I know the former can happen with Application.DoEvents (often in System.Drawing ) but I'm not sure about the latter.

Anyway, your code is evil. Don't swallow exceptions. That means you are swallowing bugs.

In general, try to avoid Application.DoEvents . There are really nasty reentrancy issues that can happen.

Attention to use the Application.DoEvents() , most of the time is used for wrong things, like update a progress bar in a time spend process, wich can be done with asynchronous programming. You can't catch all exceptions, please tell us what exception are raising.

It could also be that when you are running the application without a breakpoint, the DoEvents is allowing another piece of code to execute and that piece of code is throwing the exception.

You should check the exception's StackTrace to see where it points you (or post the stack trace here and we can look at it). If this is the case you might not be seeing the exception when you're using a breakpoint and stepping because the DoEvents and threading don't fire the same ways.

If the exception is being thrown from elsewhere during the DoEvents that would also explain why you are getting an unhandled exception even though the above code is trying to black-hole any exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM