且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在c#中捕获未处理的异常?

更新时间:2022-12-24 11:50:46

从主UI线程捕获所有异常为我工作:

  static class Program 
{
///< summary>
///应用程序的主入口点。
///< / summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

//为UI线程异常添加处理程序
Application.ThreadException + = new ThreadExceptionEventHandler(UIThreadException);

//强制所有WinForms错误通过处理程序
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

//此处理程序用于捕获非UI线程异常
AppDomain.CurrentDomain.UnhandledException + = new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

Application.Run(new Form1());
}

private static void CurrentDomain_UnhandledException(Object sender,UnhandledExceptionEventArgs e)
{
try
{
异常ex =(异常)e .ExceptionObject;
MessageBox.Show(Unhadled domain exception:\\\
\\\
+ ex.Message);
}
catch(异常exc)
{
try
{
MessageBox.Show(Fatal exception happend inside UnhadledExceptionHandler:\\\
\\\

+ exc.Message,MessageBoxButtons.OK,MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}

//应该终止我们的主线程,所以Application.Exit()在这里是不必要的
}

private static void UIThreadException(object sender,ThreadExceptionEventArgs t)
{
try
{
MessageBox.Show(未处理的异常catchched.\\\
应用程序将立即关闭);
}
catch
{
try
{
MessageBox.Show(致命异常在UIThreadException处理程序中发生
致命Windows窗体错误,MessageBoxButtons.AbortRetryIgnore,MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}

//这里我们可以决定是否要结束我们的应用程序或做别的事情
Application.Exit();
}
}


I'm trying to catch any unhandeled Exception in my program, i use this code in the Program main class

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

AppDomain.CurrentDomain.UnhandledException += new    UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

Application.Run(new Form1());
}


public static void CurrentDomain_UnhandledException(Object sender,  UnhandledExceptionEventArgs e)
{

MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled domain Exception");
Application.Exit();
}

now im my form form1, i try to create a simple exception : divide by zero, without a try catch block, the code in the main module intercepts the exception indeed, but i still have the MS Visual studio dialog. the application doesn't exit. of course in real situations, i willl log/mail the error. but i would like to understand why the execution continues after i intercept my exception ? thanks

Catching all exceptions from main UI thread worked for me:

static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Add handler for UI thread exceptions
            Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException);

            // Force all WinForms errors to go through handler
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // This handler is for catching non-UI thread exceptions
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.Run(new Form1());
        }

        private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = (Exception)e.ExceptionObject;
                MessageBox.Show("Unhadled domain exception:\n\n" + ex.Message);
            }
            catch (Exception exc)
            {
                try
                {
                    MessageBox.Show("Fatal exception happend inside UnhadledExceptionHandler: \n\n"
                        + exc.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                finally
                {
                    Application.Exit();
                }
            }

            // It should terminate our main thread so Application.Exit() is unnecessary here
        }

        private static void UIThreadException(object sender, ThreadExceptionEventArgs t)
        {
            try
            {
                MessageBox.Show("Unhandled exception catched.\n Application is going to close now.");
            }
            catch
            {
                try
                {
                    MessageBox.Show("Fatal exception happend inside UIThreadException handler",
                        "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
                }
                finally
                {
                    Application.Exit();
                }
            }

            // Here we can decide if we want to end our application or do something else
            Application.Exit();
        }
    }