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


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;          
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.


Lisa kommentaar »

Kommentaare veel pole.

RSS feed for comments on this post. TrackBack URI

Lisa kommentaar

Täida nõutavad väljad või kliki ikoonile, et sisse logida:

WordPress.com Logo

Sa kommenteerid kasutades oma WordPress.com kontot. Logi välja /  Muuda )

Google photo

Sa kommenteerid kasutades oma Google kontot. Logi välja /  Muuda )

Twitter picture

Sa kommenteerid kasutades oma Twitter kontot. Logi välja /  Muuda )

Facebook photo

Sa kommenteerid kasutades oma Facebook kontot. Logi välja /  Muuda )

Connecting to %s

Create a free website or blog at WordPress.com.