How to: generate UnhandledException?

Posted by serhio on Stack Overflow See other posts from Stack Overflow or by serhio
Published on 2010-05-18T21:59:04Z Indexed on 2010/05/18 22:20 UTC
Read the original article Hit count: 286

I use this code to catch the WinForm application UnhandledException.

[STAThread]
static void Main(string[] args)
{
    // Add the event handler for handling UI thread exceptions to the event.
    Application.ThreadException += new
      System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

    // Set the unhandled exception mode to force all Windows Forms errors 
    // to go through our handler.
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

    // Add the event handler for handling non-UI thread exceptions to the event. 
    AppDomain.CurrentDomain.UnhandledException += 
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    try
    {
        Application.Run(new MainForm());
    } catch....

There I will try to restart the application. Now my problem is to simulate a exception like this. I tried before try (in main): throw new NullReferenceException("test"); VS caught it.

Tried also in MainForm code with button :

    private void button1_Click(object sender, EventArgs ev)
    {         
        ThreadPool.QueueUserWorkItem(new WaitCallback(TestMe), null);
    }

    protected void TestMe(object state)
    {
        string s = state.ToString();
    }

did not help, VS caught it, even in Release mode.

  • How should I, finally, force the application generate UnhandleldException?
  • Will I be able to restart the application in CurrentDomain_UnhandledException?

© Stack Overflow or respective owner

Related posts about throw

Related posts about testing