What is the best practice for exception handling in WinForms or WPF. I haven't found a satisfying solution so far. Some people suggest to catch the unhandled exception event. But I don't think that this is a good solution.
The problem
I have a 3 layer application. The persistence layer, the business layer and the ui layer. Instead of catching exceptions in all three layers I think the correct place to catch the exceptions are in the ui layer. So the user will get an error message and maybe there is also a way the user can 'solve' the issue (wrong data input, etc).
So the question is, is the best/correct way to surround EVERY ui-eventhandler (click event, selection changed event, etc) with a try catch block? Like this:
private void button_MouseUp(object sender, MouseButtonEventArgs e)
{
try
{
/// ...
}
catch (Exception ex)
{
// log exception
// show error to user if necessary
}
}
I know that catching all exceptions is bad. And of course you need to prevent exceptions by validating the user input data. But sometimes there will be bugs ;).
Imagine the following situation: The user makes some changes which aren't saved yet. Then he clicks a button and in the button handler is a bug. So wouldn't it be better to show a error message and let the user decide when he wants to quit the application, so that the user won't lose the unsaved data?