Monday, May 17, 2010

Dealing with Unhandled exceptions in WPF

In you App.Xaml.cs file put the following:

private void App_DispatcherUnhandledException(object sender,
System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("An unhandled " + e.Exception.GetType().ToString() +
" exception was caught and ignored.");
e.Handled = true;
}


Add the following to the App.xaml file

DispatcherUnhandledException="App_DispatcherUnhandledException"

to the Application tag of App.xaml like this:
<Application x:Class="Something.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml" Startup="Application_Startup"
DispatcherUnhandledException="App_DispatcherUnhandledException">

Dealing with Unhandled Exceptins in C#

http://www.switchonthecode.com/tutorials/csharp-tutorial-dealing-with-unhandled-exceptions

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MyApp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}

static void CurrentDomain_UnhandledException
(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;

MessageBox.Show("Whoops! Please contact the developers with "
+ "the following information:\n\n" + ex.Message + ex.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}

public static void Application_ThreadException
(object sender, System.Threading.ThreadExceptionEventArgs e)
{
DialogResult result = DialogResult.Abort;
try
{
result = MessageBox.Show("Whoops! Please contact the developers "
+ "with the following information:\n\n" + e.Exception.Message
+ e.Exception.StackTrace, "Application Error",
MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
finally
{
if (result == DialogResult.Abort)
{
Application.Exit();
}
}
}
}
}