|Deep C# - Take Exception to Everything|
|Written by Mike James|
|Thursday, 12 March 2020|
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, add a textbox and a button. All you have to do is to add a suitable handler to the Form class:
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 - just click the button and you will get a divide by zero error.
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 a release version of 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.
Buy Now From Amazon
or email your comment to: firstname.lastname@example.org
|Last Updated ( Thursday, 12 March 2020 )|