…meie igapäevast IT’d anna meile igapäev…

2011-09-23

Global exception handler in .NET console programs

Filed under: Isiklikud,Programmeerimine — Sander @ 11:11:09

Global exception handlers are a Bad Idea(tm)! You should always handle exceptions as close to their place of origin as logically possible.

That said, there is one reason to have a global exception handler: logging.

We, the programmers, are not superhumans. No matter how many precautions we take, there always is a clever idiot who finds a way to break our programs in a new and unexpected way. Or, as Rick Cook put it, “Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.”.

The idiot may be DBA, changing case-insensitive database to case sensitive, “because, y’know, man, case insensitivity is sooo Pascal”. Or client decides to “reconfigure” web server. Or user decides that all those dll files are really a security risk. Or… No matter what. There will be a time when the flying feces will hit the rotating blades. Hard.

And the client will complain that our application does not work, fix it now!!!11!! But everything is working for us just fine…

That is where the global error handler will come to the rescue – namely, we catch a previously uncaught exception and log it. What happens with the program after that is not our concern here.

So, enough blabber, gimme the code.

static void Main(string[] args)
{
  AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;          
  //...
  //Profit!                     
}
           
static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{            
  MyFavouriteLogger.LogException(e.ExceptionObject as Exception, "Unhandled exception. Terminating application!");
  //Exit gracefully with a message and Environment.Exitcode
}

There are several gotcha’s with AppDomamain.UnhandledException, read about those from MSDN. You can use it with WinForms, but for WinForms there is Application.ThreadException as well.

About these ads

1 kommentaar »

  1. You don’t want to sign up for every company’s newsletter or you’ll soon be buried under endless emails.

    kommentaar kirjutas online shopping — 2014-04-19 @ 02:51:12 | Vasta


Selle postituse kommentaaride RSS-voog. TrackBack URI

Lisa kommentaar

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Muuda )

Twitter picture

You are commenting using your Twitter account. Log Out / Muuda )

Facebook photo

You are commenting using your Facebook account. Log Out / Muuda )

Google+ photo

You are commenting using your Google+ account. Log Out / Muuda )

Connecting to %s

The Rubric Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 68 other followers