Usually I put all of my Main method code inside of a try/catch block like so:
public static void Main(string[] args)
{
try
{
// code
}
catch (Exception e)
{
// code
}
}
I do this just in case any exceptions manage to slip out of the rest of the program logic, thus allowing me to do something about it, such as display it to console, log it to a file, etc. However, I have been told that this is bad practice.
Do you think it is bad practice?
Best Answer
Wrapping any piece of code in a
try
/catch
block without a good reason is bad practice.In the .NET programming model, exceptions should be reserved for truly exceptional cases or conditions. You should only try to catch exceptions that you can actually do something about. Furthermore, you should should hardly ever catch the base
System.Exception
class (but rather prefer to catch the more specific, derived exception classes you can handle). And should a truly unexpected exception be encountered during the course of your program's execution, you actually should crash.Obviously the "correct" answer would have to be made on a case-by-case basis, depending on what's going on inside that
// code
placeholder in yourcatch
block. But if you're asking for a general rule or "best practice", you should always have a specific reason to catch exceptions, not just wrap all of your code in a gianttry
/catch
block as a matter of course without thinking about it.Note that if you're simply trying to catch any unhandled exceptions that might occur for the purposes of logging or error reporting, you should be using the
AppDomain.UnhandledException
event. This is a notification-only event, so it doesn't allow you to handle those exceptions, but it is the right place to implement your logging or error reporting functionality after your application has crashed.EDIT: As I was catching up on my reading of Raymond Chen's excellent blog, "The Old New Thing", I noticed that he had recently published an article on a similar topic. It's specific to COM, rather than the .NET Framework, but the general concepts regarding error handling are equally applicable to both environments. I thought I'd share a couple of gems from the article here, in support of my [apparently quite controversial] opinion.
You can [and should] read the whole article here on his blog: How to turn off the exception handler that COM "helpfully" wraps around your server.