Is there a way in C# to catch all exceptions from a Control/Form?
-
05-07-2019 - |
Question
I'd like to have something like a "catch-all" for exceptions thrown from a inside a Control or a Form that reside within the current thread, but without resorting to using the Application.ThreadException
of the entire thread.
Why? Because I'd like to keep the exception handling modular.
All the code that can cause the problems is being run within a Form (DummyForm
) that is running within the current thread. I'd like to be able to wrap all of them in some other exception (DummyFormException
) that would identify that Form as the cause of the exception, so that if that exception makes it to the Application.ThreadException, I can know that the cleanup involves closing DummyForm
.
The alternatives, as I see them, are:
# Wrap every single thrown exception in the DummyForm
with a DummyFormException
. I don't like this so much, since it requires future programmers to remember to wrap each thrown exception, too.
# Run the DummyForm
in its own thread, and use Application.ThreadException
to catch them, and identify the thread inside that code. Once I know where it comes from, I could simply close the DummyForm
and end the thread.
Is there any way to do this without going multi-threaded? I'd hate to do it, it seems a waste just for error-handling. Or am I going about this all wrong?
Solution
I'm not sure it's a good idea to put all the error handling code in a single place.
Error handling should better take place next to the operation it handles.
The whole point of error handling is to change the program behaviour where the program encounters an error. This means you have to write specific code at that location, and that you can't put everything in only one place as you seem to want to.
However, maybe what you need is only an helper method to log stuff, etc.
Unhandled exceptions handlers (Application.ThreadException, AppDomain.CurrentDomain.UnhandledException) do exists, but that's not what they are for.
You should use those to handle unexpected exceptions, ie, something wrong occurred that you didn't think of, and you want to handle this case nicely (For example, you may want to log the error, or display a nice error box to the user, or gently close the program)
If you know an Exception may occur somewhere, that "somewhere" is the good place to write your exception handling code.
OTHER TIPS
Listen to Brann, otherwise you might end up on thedailywtf.com :-)
Leaving it to a global error handler will cause you all sorts of pain. Make sure any exceptions in your application are handled at the source - that's the point at which you have the right information to decide how to handle it.