如何在c#中捕获未处理的异常? [英] how to catch an unhandled exception in c#?

查看:259
本文介绍了如何在c#中捕获未处理的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获程序中的任何未处理的异常,我在程序主类中使用此代码

  static课程课程
{
///< summary>
///应用程序的主入口点。
///< / 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异常)。消息,未处理域异常);
Application.Exit();
}

现在我的表单form1,我尝试创建一个简单的异常:除以零,没有try catch块,主模块中的代码确实拦截异常,但我仍然有MS Visual studio对话框。应用程序不会退出。当然在实际情况下,我会记录/邮寄错误。但是我想了解为什么我在拦截我的异常之后继续执行感谢

解决方案

从主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();
        }
    }

这篇关于如何在c#中捕获未处理的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆