简体   繁体   English

无法捕获C#WPF中未处理的异常消息

[英]Cant catch unhandled exception message in c# WPF

I Use the AppDomain.UnhandledException Event to catch unhandled exceptions. 我使用AppDomain.UnhandledException事件捕获未处理的异常。 I use a MessageBox.Show() instead of Console.WriteLine in the example; 在示例中,我使用MessageBox.Show()代替Console.WriteLine

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: 相反,我在UnhandledExceptionEventHandler ex.Message返回以下内容:

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. 在WPF中,如果在通过XAML实例化UIElements (包括Windows)时发生异常,则框架的XAML / BAML引擎将创建其自身的异常,并将原始异常放入其InnerException属性中。

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 . 此处以catch块形式给出的示例可以以相同的方式应用于UnhandledExceptionEventHandler

Your code is not running in full trust. 您的代码未完全信任运行。 Add the permissions on the method 在方法上添加权限

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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