UnhandledException?

How could i capture & handle UnhandledException in client or service side

Answer this question

UnhandledException?

  • Gunnar Hansen

    this is the sample that i copy from the MSDN help, bear in mind that AppDomain.UnhandledException will halt your application when it happen in most cases, a better way to deal with unhandled exceptions it System.Windows.Form.Application.ThreadException  for a Windows Form app, while on the service( ASP.Net) take a look at HttpApplication.Application_Error( Global.asax)


    public static void Main() {
       AppDomain currentDomain = AppDomain.CurrentDomain;
       currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
       
       try {
          throw new Exception("1");
       } catch (Exception e) {
          Console.WriteLine("Catch clause caught : " + e.Message);
       }

       throw new Exception("2");

       // Output:
       //   Catch clause caught : 1
       //   MyHandler caught : 2
    }

    static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
       Exception e = (Exception) args.ExceptionObject;
       Console.WriteLine("MyHandler caught : " + e.Message);
    }

  • bassmanyoowan

    Erymuzuan,

    Where do i have to put this "Main" method  
    Or i just need to add a handler in _load event and call MyHandler.

    Please let me know. 

  • FFil

    The "Main" method is actually the assembly's entry point, every assembly should have one( or more, the you have to choose which one), when you create a Windows Form App using visual Studio.Net, it will create one in Form1.cs/Form1.vb, here you'll find,  Application.Run(new Form1()); so if you wanna use the exception handling above you have to do this



    public static void Main() {

       AppDomain currentDomain = AppDomain.CurrentDomain;
       currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
       Application.Run(new Form1());


    }



    static void MyHandler(object sender, UnhandledExceptionEventArgs args) {

       Exception e = (Exception) args.ExceptionObject;
       //
       // do soemthing meaningful here
       Console.WriteLine("MyHandler caught : " + e.Message);

    }




  • Belzicool

    See AppDomain.UnhandledException and Application.ThreadException
  • UnhandledException?