How do you handle Exceptions in your .NET code? I always catch exceptions I'm expecting (like a "directory not found" error) and try to resolve it without bothering the user. If it can't be resolved, I write the message & stack trace to an error log, then rethrow the Exception to allow it to bubble up. Another "developer" and I had an argument recently about this practice, mainly because of critical comments I made about his code. Specifically, he uses the following code as a stub for all methods:
private void ExampleMethod(){ try{ //some code here } catch { throw; } }
So basically he catches all errors and then rethrows them immediately. I asked him what logic was behind that design choice and he told me that he doesn't trust the .NET Framework to handle all errors, so it's best to follow this practice. Also, this will insure that errors bubble up to the caller. Apparently he adapted it from someone he used to work with.
I have a few problems with this argument...
- If you "don't trust" the .NET Framework to handle Exceptions, why do you trust it to catch & rethrow them??
- A naked "catch" block will catch non-CLS compliant code, which can only be introduced via COM or some really sketchy manual compilation. So if your method is calculating the volume of an egg and does not call any 3rd party dlls, why are non-CLS compliant exceptions a concern?
We had this e-mail exchange:
E-mail #1
Ken, Specifically, this Microsoft recommendation seems to back up my main argument for not re-throwing an Exception
"Use Inner exceptions (chained exceptions). However, do not catch and re-throw exceptions unless you are adding additional information or changing the type of the exception."
Jerry
E-mail #2
Jerry, that's true I found out about it, but it look so unstructured, it is what's in the framework, less work for us. However look at it in terms of distributed environment, this won't work. Example Client.A() call web service B(), since B() is ws business layer with passive exception handling, when error occurred in datalayer ws is using error wont bubble up to the client. It's error accessible in local framework.
Anyone else want to weigh in on this?
References Best Practices for Handling Exceptions .NET Framework Developer's Guide : Exception Handling Unexpected Errors in Managed Applications
|