Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch an unhandled exception in c#?

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

like image 927
user1327073 Avatar asked Dec 27 '22 01:12

user1327073


1 Answers

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();
        }
    }
like image 176
lucask Avatar answered Jan 04 '23 16:01

lucask