Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch unhandled exceptions from any thread

Edit

The answers to this question where helpful thanks I appreciate the help :) but I ended up using: http://code.msdn.microsoft.com/windowsdesktop/Handling-Unhandled-47492d0b#content


Original question:

I want to show a error message when my application crashes.

Currently I have:

App.xaml:

<Application x:Class="WpfApplication5.App"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      DispatcherUnhandledException="App_DispatcherUnhandledException"  // <----------------
      StartupUri="MainWindow.xaml">
    <Application.Resources>             
    </Application.Resources>
</Application>

Code-behind of App.xaml:

namespace WpfApplication5
{        
    public partial class App : Application
    {
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show("Caught Unhandled Exception!");
        }
    }
}

That solution works great when the error occurs on the main thread. Now my problem is how will I be able to catch errors that happen on a different thread also?

In other words: when I press this button I am able to catch the exception: (App_DispatcherUnhandledException gets called!)

    private void button1_Click(object sender, RoutedEventArgs e)
    {            
        int.Parse("lkjdsf");
    }

But I am not able to catch this exception:

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Task.Factory.StartNew(() =>
        {
            int.Parse("lkjdsf");
        });
    }

How will I be able to catch all exceptions regardless if they happen on the main thread or not?

like image 704
Tono Nam Avatar asked Mar 20 '13 14:03

Tono Nam


2 Answers

You can use AppDomain.UnhandledExceptionHandler to handle uncaught exception.

like image 170
Tilak Avatar answered Oct 23 '22 18:10

Tilak


Use AppDomain.UnhandledException event to catch this exception. than you need to use the dispatcher to be able to show this exception in a messageBox (this is because only ui thread can show messages)

like image 24
omer schleifer Avatar answered Oct 23 '22 18:10

omer schleifer