Sunday, March 8, 2009

Catch (Exception e): Right or wrong?

I've long heard that you shouldn't throw a type Exception in C#. I try to always throw a type derived from Exception.

In addition, I've also read many brief snippets over the years that says you shouldn't write C# code like:

catch(Exception e)
{
...
}

I recently read the best explanation of this in Microsoft's MSDN Magazine (Feb. 2009). The article is entitled Handling Corrupted State Exceptions and would highly recommend those programming in C# to read the full article. It also provides details about how exception handling will change a bit in .NET 4.0.

A read well worth it!

http://msdn.microsoft.com/en-us/magazine/dd419661.aspx

2 comments:

DOTNETWORLD said...

Great article. But he doesn't really give a good alternative solution. He says "catching a specific exception is the correct thing to do because it provides the most context to your exception handler."

Every class in C# throws 4-5 exceptions and more in some cases. Are we expected to know these and catch each specific?

Do you think its a good idea not to use try/catch at all (or only in certain specific situations where you exactly know that specific exception(s)) and let the code throw server error, so you as a developer can handle that situation in code?

For example: Let it throw NullException, so you can check for null in code:
if(someObj == null) { }


Usually people use catch(Exception) in the unknowing that there might be some creepy thing happening Or in some cases they are afraid their customers might see the yellow screen of death (Server Error).

I think Java is better in this aspect, as it expects/forces the programmer/developer to follow a pattern...

How do you handle unknown situations?

Thanks for posting, a great read..

PaulTechGuy said...

Kirroti,

I would agree that Java has a better pattern in that it forces you to know and handle any exceptions that would occur in your code.

The main idea behind not catching Exception is that in just about all cases you really don't know what the issue is; therefore how can you handle it? Probably even worse it that if you make an attempt to handle it, you may end up with a system still running, but in a corrupted state. Who knows what this may do to your data or even security model as the application continues to execute.

About the only time I use catch is when catching a very specific type in a local scope, or at the very top-level of an application (in which case it logs the error and exits).

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...