Handling Generic Exceptions in Windows Forms
I have had the opportunity to face interesting and curious exceptions which seems to act like a mouse evading all attempts at capture. In addition, I have recently been dabbling more into the integration aspect of software development meaning I need to learn and anticipate user interaction with the system.
One of the things which makes an application great is fantastic robustness and automatic help. For example, how would you feel if you Windows stops working everytime a small bug or error happen for instance when you click on the wrong file to open? Isn't great how it just keeps going and going and going and.... you get the picture. (Ahh... of course I'm referring only to Windows XP, not the previous version ;-) ). What I use to do, what I learnt before is to selectively add in Try ... Catch ex as Exception in parts of the code at the top most level to handle any possible unhandled exceptions and display message to user to inform them.
An alternative which I learnt about was to use a Shared Sub Main() as the entry point to the application, call Application.Run(MainWinFormOfApplicationObject) and put within a Try ... Catch ex As Exception block. However this still does not catch some exceptions which might occur.
Now there is a better way. The aforementioned methods can work sometimes but as mention above, you will still get unhandled exceptions coming seemingly from nowhere. There is a static/shared event under the Application namespace (Application.ThreadException) which allows you to handle all exceptions coming from the application. All you need is to create an event handler and wire up to this event.
The reason behind all this is because in Windows Forms, all the UI aspects e.g. close button ('X'), minimize/maximize buttons, resizing window e.t.c. are run on a separate thread from the application itself. Therefore when the UI throws an exception, it is throwing on it's own thread and the Try ... Catch ex As Exception around Application.Run() will not catch anything since there was no exception thrown within anyway!
A couple of good places to start learning this with:
Managing Unhandled Exceptions in dotNET ~ CodeProject.com
Unhandled Exception Handler ~ GeeksWithBlogs.net
However do be careful and take note that not everything works
C# IAQ #6: Why Can't I Throw An Exception in GUI Thread and Let Application.ThreadException Handle It? ~ GeeksWithBlogs.net
I'm still pretty new with this and due to other constraints am unable to pursue knowledge of this further. I will most definitely have a more detailed look at this very very interesting aspect of Windows Forms programming. Console and Web programming (ASP.NET) has their own versions of Application.ThreadException and different usage patterns.

1 Comments:
Nice one! :)
Thursday, December 22, 2005 10:18:00 PM
Post a Comment
<< Home