Page 5 of 5
The ultimate custom exception handler
There is a little-known facility whereby you can take over exception handling within your application.
All you have to do is set up a ThreadException handler.
Assuming you are starting from a standard forms project all you have to do is to add a suitable static handler to the Form class:
public static void threadErrorHandler(
"hello unhandled exception");
You also need to add:
Next you need to open the Program.cs file and change the application run to read:
static void Main()
The two new statements set the UnhandledException mode so that any unhandled exceptions are passed to the event handler and set up the event handler.
You also need to add the same using statement and raise a suitable exception in the application to test things.
Now if you try the application out you will discover that it doesn't work! The reason is that running the application in the debugger overrides the event handling and the debugger shows you the exception to give you a chance to fix the problem. To see the event handler in action the simplest thing to do is build the application, navigate to the bin/release directory and run it without the intervention of Visual Studio.
Alternatively if you plan to develop something like this further set the Visual Studio option Debugging to disable the exception assistant. After this you will be told that an exception has occurred but you have the choice of terminating or continuing. Selecting Continue calls the event handler.
It is clear that exception handling is far from easy and far from a solved problem. Exploratory testers often say that a vague error message along the lines of
"Something is wrong - I have to close now"
is a sign that it was generated by an exception and a precise error message e.g.
"Price cannot be negative"
is a a sure sign that it was generated by a specific conditional test. This gives you a very clear idea of the state-of-the-art in exception handling.
We can do better.
Careful design of program logic and using exceptions only when absolutely essential is good advice.
Exploratory Software Testing
C# Design and Development:
If you would like to be informed about new articles on
I Programmer you can either follow us on Twitter, on Facebook or you can subscribe to our weekly newsletter.
Each provides a full list of what's new each week - usually five hot book reviews, five thought-provoking articles and five not to be missed news items - in a compact click-to-read form.