Usually the recommendation is to use Application.DispatcherUnhandledException Event
:
public App() :base() {
this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}
public partial class App : Application {
void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) {
// Faz o que quiser aqui.
e.Handled = true;
}
}
Another form that can be used if you want to do one last action when you are already dismounting WPF:
[System.STAThreadAttribute()]
public static void Main() {
WpfApplication1.App app = new WpfApplication1.App();
app.InitializeComponent();
try {
app.Run();
} catch (Exception ex) { //aqui é um bom local para por esta captura geral
//faz algo aqui
}
If you have a method onStartup()
in the derived class of Application
, can be a good place to put something too. It depends on how it was built.
You really should not be spreading try-cath
across every application. But you have a place you need. That is the last measure, is when everything failed, when it did not have in the to solve more specifically. And many mistakes are just the same. But do not think you did that, you no longer have to worry about exception handling in a localized way. That would be radicalism as opposed to what people usually do.
What you can even do is create a library of common actions that should be performed when an exception occurs, then call these actions within the appropriate catch
. People often forget that "anything" in the code that is going to run more than once should be part of a library, should be generalized, either to eliminate repetition, or to be more DRY .
But the catch of the exception must be more localized. The exception should be captured at the right time, either before or after the best time.
try-catch
is a structure that controls the flow of the application, so it can not be placed anywhere. And it is even more complicated than other structures because it can produce global side effects. Great care is needed with its use.
Of course you do not need to put in everywhere, this is the common mistake. And almost always the exceptions will not be thrown in the WPF part itself.
If you are in doubt about the correct use, you will have to ask specific questions when using it in every dubious situation until you get accustomed.