4

In ASP.NET I can use Application_Error within global.asax in order to handle any errors that have been unhandled.

Is there an equivalent in windows forms?

m.edmondson
  • 29,632
  • 26
  • 117
  • 199

3 Answers3

2

Yes its AppDomain.UnhandledException


using System;
using System.Security.Permissions;

public class Test {

   [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
   public static void Example()
   {
      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);
   }

   public static void Main() {
      Example();
   }
}
WraithNath
  • 17,078
  • 9
  • 52
  • 80
1
[STAThread]
static void Main()
{
  Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
  Application.Run(new FrmMain());
}

private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
  MessageBox.Show("Unhandled exception: "+e.Exception.ToString());
}
Vlad Bezden
  • 72,691
  • 22
  • 233
  • 168
0

It depend on the architecture of your app. For exemple, if you do MVC architecture then it should be in your controler.if you know Chain of responsability pattern[GOF] or if you prefer a big handler of all type of execption. Otherwise, you'll to tell us more about your app.