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

时间:2014-06-12 19:45:07

标签: c# wpf unhandled-exception

我使用AppDomain.UnhandledException Event来捕获未处理的异常。我在示例中使用了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 displays the following output: 
//       Catch clause caught : 1 
//        
//       MyHandler caught : 2 

ex.Message中的UnhandledExceptionEventHandler会返回此信息:

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'.

当我希望它返回示例显示的内容时:

MyHandler caught : 2

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

在WPF中,如果通过XAML实例化 UIElements (包括windows)时发生异常,则框架的XAML / BAML引擎会创建自己的异常并将原始异常放入其 InnerException 属性。

因此,要获取完整的异常信息,您可以在异常处理程序中执行与以下类似的操作:

    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);
    }

此处以catch-block形式给出的示例可以以相同的方式应用于 UnhandledExceptionEventHandler

答案 1 :(得分:0)

您的代码未完全信任。添加方法

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