首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在 Application.ThreadException 事件处理程序中获取整个异常链?

在 Application.ThreadException 事件处理程序中获取整个异常链,可以通过递归地处理异常的 InnerException 属性来实现。以下是一个示例代码:

代码语言:csharp
复制
using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException((Exception)e.ExceptionObject);
        }

        private static void HandleException(Exception ex)
        {
            string message = GetExceptionMessage(ex);
            MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Exit();
        }

        private static string GetExceptionMessage(Exception ex)
        {
            string message = ex.Message;

            if (ex.InnerException != null)
            {
                message += "\n\nInner Exception:\n" + GetExceptionMessage(ex.InnerException);
            }

            return message;
        }
    }
}

在上述代码中,我们在 Main 方法中注册了 Application.ThreadException 事件处理程序和 AppDomain.CurrentDomain.UnhandledException 事件处理程序,以便在发生未处理的异常时进行处理。HandleException 方法用于处理异常,GetExceptionMessage 方法用于递归地获取整个异常链的消息。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券