微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 在Application_UnhandledException事件中从StatckTrace获取Method,Class和LineNumber

我正在开发Windows Phone 7 Silverlight应用程序.我想进行应用程序级错误处理,而不是在所有方法中编写try … catch …我需要提取实际错误发生的方法名称,类名称和行号.以下是演示代码.在Application_UnhandledException事件中,我期待Method =“GenerateError”和Class =“ExceptionTesting”.另外,我想让LineNumber发生实际错误(代码中没有显示).

生成错误代码

public partial class ExceptionTesting : PhoneApplicationPage  
{
    // Generate Error to Test Exception Handling
    private void GenerateError()
    {
        Int16 i = Convert.ToInt16("test");
    }
}

处理应用程序级别异常的代码

// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
StackTrace st = new StackTrace();

var query = st.GetFrames()         // get the frames
        .Select(frame => new
        {                   
            Method = frame.getmethod(),
            Class = frame.getmethod().DeclaringType
        });

foreach (var q in query)
{
    if (q.Method.Name.Contains("GenerateError"))
    {
        MessageBox.Show("Class: " + q.Class + ", Method: " + q.Method);
    }
}

if (System.Diagnostics.Debugger.IsAttached)
{
    // An unhandled exception has occurred; break into the debugger
    System.Diagnostics.Debugger.Break();
}
}

解决方法:

不会从发生异常的方法调用Application_UnhandledException方法,因此新的StrackTrace()将没有意义,正如您所发现的那样.

获取发生异常的位置的堆栈跟踪,请使用e.Exception.StackTrace.
请注意,真正的异常可能包含在另一个异常中,可能是几层深(e.Exception.InnerException).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐