Raw, non-ui stream, exceptions in Windows Forms

Aside from putting a try / catch block in every workflow method, is there a way to deal with unhandled non-ui thread, exceptions in Windows Forms?

Thread.GetDomain().UnhandledException

great for catching the error, but by then it's too late to do anything (other than the log). After control leaves your handler UnhandledException

, the application exits . The best you can hope for is a common Windows error that looks like this:

http://i40.tinypic.com/2be98i.jpg

All my research shows that you should insert a try / catch block in a workflow method, but I would like to put it there in case anyone else had a case.

Thank.

+1


source to share


4 answers


If you want to do something about the error before it gets caught in an UnhandledException, you need a try / catch on the stream method.



You should at least handle exceptions like FileNotFoundException where you can do something smart. If all else fails, you can use an UnhandledException to completely handle anything you didn't expect (which, hopefully, nothing.)

+2


source


Thread.GetDomain (). UnhandledException goes to AppDomain.UnhandledException , which will usually be the same domain for all threads in your application - in other words, you only need to bind this event once, not once per thread.

unhandled exceptions on secondary threads will kill the thread. see SafeThread for an alternative



caveat: I am the author of SafeThread

+1


source


Sounds like you misunderstood ... You are not putting code "in" a thread. You run the code "on" the thread.

Wherever you put the try catch block, it can be run on any thread ... if you want the code in the catch to do something (manipulate) the UI element, you just need to "run" that code on any thread the elements user interfaces have been created (if needed).

Each WinForms UI Element has two members to help you do this, InvokeRequired (), which returns a boolean value if it is executed on any thread other than the thread the element was created on (in which case, you must switch threads), and BeginInvoke (), which automatically switches to the correct stream.

0


source


To handle the exception, you must insert a try / catch block inside the code that runs on the thread.

If you think about it, then UnhandledException is actually a well-named one. The exception was "not handled" and therefore there is nothing you can do about it. Too late!

Indeed, outside of the context of a thread, there isn't much that you can do to "save" it from crashing, since you have no context to fix it. As such, UnhandledException is useful for logging and trying to determine why something happened after a crash.

If you're thinking about how try / catch works:

try
{
  // run this code

}
catch (Exception ex)
{
  // an exception happened in the above try statement inside MY thread
}

      

0


source







All Articles