开发者

How to gracefully close a form if an exception occurs on that form in C#

开发者 https://www.devze.com 2023-04-03 09:53 出处:网络
I am in a position where I have a large user app that has quite a 开发者_运维百科few forms and I am looking for a way to close a single form if an exception has occurred due to some logic that has bee

I am in a position where I have a large user app that has quite a 开发者_运维百科few forms and I am looking for a way to close a single form if an exception has occurred due to some logic that has been caught on that form.

Right now I am following the principal of 'don't write try/catch everywhere to catch boneheaded mistakes' and it does make my code cleaner, but causes crashes the entire app when I have a NullPointerException.

The best solution would be a 'local error handler' that each form would have that would collect any exceptions at that level and kill the form there instead of it bubbling up and killing the entire app.

Anyone have any ideas?


but causes crashes the entire app when I have a NullPointerException.

Then you need to fix the NullReferenceException(s), not come up with some convoluted mechanism for catching exceptions at the global level and backtracking to find the form which caused it. You should simply (try to) design your code so that null references are impossible to occur, or if they do, it can be handled in a graceful manner.

If you have a scenario which causes a crash, fix it, don't ignore it. How can you guarantee that closing the form will leave your program in a consistent state, now and in the future? (HINT: You can't)


Can you derive your forms from a common base class, so they can share the same error handler? We have a base form that logs the exception, displays an error, and then closes the form (which is optional in debug mode). Every user event (button_click for example) is wrapped in a try/catch that calls the base error handler.

Also, in case you didn't know, there are global exception handlers:

Application.ThreadException event

AppDomain.UnhandledException event

WindowsFormsApplicationBase.UnhandledException event (VB)

0

精彩评论

暂无评论...
验证码 换一张
取 消