Pregunta

I'm trying to handle exceptions in a dialog so that if any exception occurs, the dialog will be closed and the application will not crash. As you can see, I use a simple try-catch block:

IDialogView dialog = null;
try
{
    if (_dialogViewModel == null)
    {
        dialog = ViewFactory.SomeDialog();
        _dialogViewModel = new DialogViewModel(dialog);
        _dialogViewModel.LoadData();
    }
    _dialogViewModel.ShowDialog();
}
catch (Exception ex)
{
    if (dialog != null)
        dialog.Close();
    _dialogViewModel = null;
    MessageBox.Show("Sorry, there was an error in the dialog.", "Error",
                    MessageBoxButton.OK, MessageBoxImage.Error);
    return;
}

The problem happens when an error occurs in button's CanExecute() event handler. Error is successfully caught, but when I show the MessageBox to the user, CanExecute() executes again, and so the error happens again. In the end it results in application crash.

I've googled some info, and it were said to make sure that there is no exceptions in CanExecute() event handler. But something like this can happen somewhere else, and that's why I want to simply catch ALL exceptions in the dialog entry point without working with every method.

So, my question is: how to destroy the dialog so that after exception catch it won't show again anymore? Close() didn't work, because before closing it still calls CanExecute().

¿Fue útil?

Solución

As you found when you googled, you should make sure that a CanExecute handler is a) lightweight and b) never throws an exception. You are running into the main reason for this: a CanExecute will be run repeatedly, and automatically, by the framework. It will run when focus changes, on input events, when databindings change, and in response to a number of other reasons that you have little to no control over.

The problem is: you do have an error, and that error is occurring repeatedly. That means you can choose between crashing, or showing the dialog repeatedly. Or, you can do something about the error.

Your answer: fix the error.

(Your handler as it stands is fine for your other errors. Leave it there. But this particular error, you need to fix right away.)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top