Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 267259
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T23:31:17+00:00 2026-05-11T23:31:17+00:00

First let me say I have read this useful article thoroughly and am using

  • 0

First let me say I have read this useful article thoroughly and am using the SafeThread class from CodeProject. I get the same result whether using Thread or SafeThread.

I have reduced my problem down to an app consisting of two forms each with one button. The main program displays a form. When you click that button, a new thread starts which displays a second form. When you click the button on the second form, internally it just does “throw new Exception()”

When I run this under VS2008, I see “Exception in DoRun()”.

When I run outside of VS2008, I get a dialog box “Unhandled exception has occurred in your application. If you click continue, the application ….”

I have tried setting legacyUnhandledExceptionPolicy in the app.config to both 1 and 0.

What do I need to do to capture the exception thrown in my second form, when not running under VS2008?

Here’s my Program.cs

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.ThreadException += new ThreadExceptionEventHandler    (Application_ThreadException);
            Application.SetUnhandledExceptionMode    (UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
               Application.Run(new Form1());
            }
            catch(Exception ex)
            {
                MessageBox.Show("Main exception");
            }                
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show("CurrentDomain_UnhandledException");
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            MessageBox.Show("Application_ThreadException");
        }
    }

Here’s Form1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SafeThread t = new SafeThread(new SimpleDelegate(ThreadMain));
        try
        {
            t.ShouldReportThreadAbort = true;
            t.ThreadException += new ThreadThrewExceptionHandler(t_ThreadException);
            t.ThreadCompleted += new ThreadCompletedHandler(t_ThreadCompleted);
            t.Start();
        }
        catch(Exception ex)
        {
            MessageBox.Show(string.Format("Caught externally! {0}", ex.Message));

        }
    }

    void t_ThreadCompleted(SafeThread thrd, bool hadException, Exception ex)
    {
        MessageBox.Show("t_ThreadCompleted");
    }

    void t_ThreadException(SafeThread thrd, Exception ex)
    {
        MessageBox.Show(string.Format("Caught in safe thread! {0}", ex.Message));
    }

    void ThreadMain()
    {
        try
        {
            DoRun();
        }
        catch (Exception ex)
        {
            MessageBox.Show(string.Format("Caught! {0}", ex.Message));
        }
    }

    private void DoRun()
    {
        try
        {
            Form2 f = new Form2();
            f.Show();
            while (!f.IsClosed)
            {
                Thread.Sleep(1);
                Application.DoEvents();
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show("Exception in DoRun()");
        }
    }
}

And here is Form2:

public partial class Form2 : Form
{
    public bool IsClosed { get; private set; }

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        throw new Exception("INTERNAL EXCEPTION");
    }

    protected override void OnClosed(EventArgs e)
    {
        IsClosed = true;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T23:31:18+00:00Added an answer on May 11, 2026 at 11:31 pm

    1.) I would recommend using the BackgroundWorker instead of separate threads like this. Your worker will catch exceptions and pass them along as a parameter to the complete handler.

    2.) I would use ShowDialog() instead of Show() when displaying the second form, this will block the DoRun() at that method call and exceptions should then be caught by your surrounding try / catch (or the BackgroundWorker if you’re using that instead).

    I think the problem comes that since you’re calling Show() you’re essentially dispatching that call onto the Invoker, which ends up being queued in the UI thread. So when an exception happens there is nothing higher up the callstack to catch it. I believe calling ShowDialog() will fix this (and also allow you to drop that nasty for loop).

    Something like this:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            // NOTE: I forget the event / method names, these are probably a little wrong.
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, e) =>
            {
                Form2 f = new Form2();
                e.Result = f.ShowDialog();
            };
            worker.DoWorkComplete += (o, e) =>
            { 
                if(e.Error != null)
                    MessageBox.Show(string.Format("Caught Error: {0}", ex.Message));
    
                // else success!
                // use e.Result to figure out the dialog closed result.
            };
    
            worker.DoWorkAsync();
        }
    }
    

    Actually, now that I think about it, it’s sort of weird to be opening a dialog from a background thread but I think this will still work.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to read some BigDecimal values from the string. Let's say I have
Let's say I have 3 point clouds: first that has 3 points {x1,y1,z1}, {x2,y2,z2},
First of all, let me say I am very new to rails, have been
First let me say that I really feel directionless on this question. I am
First, let's get the security considerations out of the way. I'm using simple authentication
Let's say I need to access a web service from an iPhone app. This
I have used an open source code from CodeProject to read email from incoming
Let's say the first N integers divisible by 3 starting with 9. I'm sure
First, let me say that I'm a complete beginner at Python. I've never learned
Let's say I have a variadic function foo(int tmp, ...) , when calling foo

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.