[英]Cant catch unhandled exception message in c# WPF
我使用AppDomain.UnhandledException事件捕获未处理的异常。 在示例中,我使用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
相反,我在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'.
当我期望它返回示例显示的内容时:
MyHandler caught : 2
谢谢您的帮助。
在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块形式给出的示例可以以相同的方式应用于UnhandledExceptionEventHandler 。
您的代码未完全信任运行。 在方法上添加权限
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.