简体   繁体   中英

Cant catch unhandled exception message in c# WPF

I Use the AppDomain.UnhandledException Event to catch unhandled exceptions. I use a MessageBox.Show() instead of Console.WriteLine in the example;

public static void Main()
{
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

    try
    {
        throw new Exception("1");
    }
    catch (Exception e)
    {
        MessageBox.Show("Catch clause caught : " + e.Message);
    }

    throw new Exception("2");
}

static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
{
    Exception e = (Exception) args.ExceptionObject;
    MessageBox.Show("MyHandler caught : " + e.Message);
}

The example says the output should be:

// The example displays the following output: 
//       Catch clause caught : 1 
//        
//       MyHandler caught : 2 

Instead my ex.Message in the UnhandledExceptionEventHandler returns this:

MyHandler caught : 'The invocation of the constructor on type 'FlashMaps.MainWindow' that matches the specified binding constraints threw an exception.' Line number '4' and line position '9'.

When I expected it to return what the example displays:

MyHandler caught : 2

Thank you for your help.

In WPF, if exceptions occur when UIElements (including windows) are being instantiated via XAML, the framework's XAML/BAML engine creates an exception of its own and puts the original exception into its InnerException property.

Thus, to get full exception information, you can do something similar to the following in your exception handler(s):

    try
    {
        ...
    }
    catch (Exception ex)
    {
        string message = "";
        string formatString = "{0}: {1}";
        do
        {
            message += string.Format(formatString, ex.GetType(), ex.Message);
            ex = ex.InnerException;
            formatString = "\n    Inner {0}: {1}";
        }
        while (ex != null);
        MessageBox.Show(message);
    }

The example given here in the form of a catch-block can be applied in the same manner to your UnhandledExceptionEventHandler .

Your code is not running in full trust. Add the permissions on the method

[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM