Hina Khuman
Hina Khuman

Reputation: 767

How to display error form App.xaml.cs in WPF Application

I'm developing one WPF application, in which I've to handle Exception globally.

For that I've refer MSDN document.

And accordingly my code on my main window:

private void TestMethod()
{  
  string s = null;      
  try
  {
    s.Trim();
  }
  catch (Exception ex)
  {
     MessageBox.Show("A handled exception just occurred: " + ex.Message, "RestartApplication", MessageBoxButton.OK, MessageBoxImage.Warning);
  }
 s.Trim();
}

In my App.xaml.cs

public App() : base()
{
    this.Dispatcher.UnhandledException += Application_DispatcherUnhandledException;

}
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    MessageBox.Show("An unhandled exception just occurred: " + e.Exception.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
    e.Handled = true;
}

Here i expecting two MessageBoxfor an exception. and seems like Application_DispatcherUnhandledException not called.

But VS gives an error on second s.Trim();

How can i handle an error and show message box from App.xaml.cs?

I've refer many links of SO like:
dispatcherunhandledexception-does-not-seem-to-work
globally-catch-exceptions-in-a-wpf-application

Update : Real time application code, were second message box not displaying :

private void ListProcesses()
{
    string s = null;

    Process[] localByName = Process.GetProcessesByName("notepad++");

    DateTime test = new DateTime();
    try
    {
        s.Trim();

        foreach (Process p in localByName)
        {

            this.Dispatcher.Invoke(() =>
            {
                if (storevalue != p.MainWindowTitle && !String.IsNullOrEmpty(p.MainWindowTitle))
                {
                    aTimer.Stop();

                    this.Visibility = Visibility.Visible;
                    this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    this.Topmost = true;
                    this.WindowState = System.Windows.WindowState.Maximized;
                    this.ResizeMode = System.Windows.ResizeMode.NoResize;
                    storevalue = p.MainWindowTitle;
                }

            });
        }
    }
    catch (Exception ex)
    {
        aTimer.Stop();
        MessageBoxResult result = MessageBox.Show("A handled exception just occurred: " + ex.Message, "RestartApplication", MessageBoxButton.OK, MessageBoxImage.Warning);                                          
    }

    s.Trim();
} 

Upvotes: 2

Views: 2430

Answers (2)

AnjumSKhan
AnjumSKhan

Reputation: 9827

Remove your try / catch blocks, and run "Start Without Debugging (Ctrl+F5)" .

Application.DispatcherUnhandledException Event 

is fired only by unhandled exceptions.

This is what I did :

public partial class Window12 : Window
{
    public Window12()
    {
        InitializeComponent();

        string id = null;
        id.Trim();
    }
}

App.xaml.cs

public partial class App : Application
{
    public App()
    {
        this.DispatcherUnhandledException += App_DispatcherUnhandledException;
    }

    void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        MessageBox.Show("Unhandled exception occured > " + e.Exception.ToString());
    }
}

Upvotes: 0

Pikoh
Pikoh

Reputation: 7713

Erm..I think I know what is happening to you. The Dispatcher.UnhandledException event only works when the app is running, not when you run it from the Visual Studio. Try to run it from the Debug folder for example, and i think you'll see the expected behaviour.

When you run your app from Visual Studio, VS itself is handling the exception so it would never be unhandled, thus never firing the Dispatcher.UnhandledException event.

EDIT

Ok, after studying your code, i guess your ListProcesses method is running in a Timer. Timers does not pass the exceptions to the calling thread, so it would never work. If you are using System.Timers.Timer it will silently swallow exceptions and if you use System.Threading.Timer will terminate the program.

So in that case, you'll need to take care of the Exceptions yourself, sorry :)

Upvotes: 1

Related Questions