3

Is there a way to centralize the error handling or exceptions handling without using try catch methods?

djot
  • 2,952
  • 4
  • 19
  • 28
Pradeep
  • 2,639
  • 11
  • 36
  • 45
  • Are you interested in centralized error fallback, so that you can log and display a friendly message before shutting down the application or are you talking about a central place to actually handle errors. The former case is supported by `Application.ThreadException` (in WinForms) and `AppDomain.UnhandledException`. The latter case is generally not possible, as there is usually not enough context in a central location to make decisions about how to recover from errors. – Dan Bryant Sep 13 '10 at 13:25

4 Answers4

8

Use AppDomain's UnhandledException event:

    static void Main(string[] args)
    {

        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    }

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        // log the exception 
    }

For ASP.NET use you will use glabal.asax.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
2

If this is for ASP.NET you can add a Global.asax file to the website and handle the Application_Error method.

This is how I generally use it:

void Application_Error(object sender, EventArgs e) 
{ 
    // Code that runs when an unhandled error occurs
    if (!System.Diagnostics.EventLog.SourceExists("MySource"))
    {
        System.Diagnostics.EventLog.CreateEventSource("MySource",
            "Application");
    }
    System.Diagnostics.EventLog.WriteEntry("MySource",
        Server.GetLastError().ToString());
}
Codesleuth
  • 10,321
  • 8
  • 51
  • 71
  • Incase the OP was't aware though, the stuff in that method about EventLog etc isn't required - you can handle it anyway you want. The important bit is the signature of the method in Global.asax and `Server.GetLastError()` which gives you the most recently thrown exception. – Michael Shimmins Sep 13 '10 at 11:17
0

You could try AOP based addons like PostSharp that injects your exception handling code to your classes and/or methods that have custom attributes. This is done post-compile, so your source code remains clean. Check this out - http://www.sharpcrafters.com/postsharp/documentation/getting-started

Hari Pachuveetil
  • 10,294
  • 3
  • 45
  • 68
0

If you are using WinForms, you could have a look at my other answer related to this. It does use try-catch though, as there is no other way that I know off.

See other answers for ASP.NET and possible other .NET uses.

Community
  • 1
  • 1
peSHIr
  • 6,279
  • 1
  • 34
  • 46