Thursday, June 15, 2006

The case against catch(Exception ex)

You should definitely read this fine article about exception handling. When it comes to exception handling, there is still a lot of confusion amongst us, developers. With all the recent ramblings and hypes about WTF, WCF, WWF, ... whatever, why don't we just start implementing exceptions the right way. The article defends why there is a rule in FxCop that specifies that it's not a good thing to catch exceptions of type Exception. I feel that the C# compiler should raise an error when writing something like this: try { // Do something } catch(Exception ex) { // Rethrow or swallow (doesn't matter, it's pure evil!!) } I must admit, even writing this syntax now does make me feel bad. Quote: If a bug in your code manifests itself as an exception (and most of the ‘unchecked’ exceptions are just that), then it’s best to let the application terminate right at the point of failure. When the bug is discovered, you’ll get exactly the diagnostic information you need to fix it quickly, add the appropriate regression tests, and move on. On the other hand, debugging a system which aggressively swallows general exceptions feels like you’re one of the police investigators in “CSI: Miami”. The culprit has left the crime scene and you have to work backwards from the subtle clues in your program’s incorrect behavior. One should only catch an exception when he can do something about it. When you can't make up a valid reason to catch an exception, then just let it go. When it kills your application: fine! You discovered a bug that needs your attention, and all the information is right there. Quote: And that’s the principal reason to avoid catch (Exception): it hides bugs in your code. These bugs are far more costly to resolve and since they can go undetected, the quality of your software suffers. There are just a few cases where using a general exception handler is justified. The one use case scenario I can come up with is an application that uses plugins (potentially third-party). I would consider running the plugin code in a general exception handler in order to prevent malicious code from bringing down my application. Maybe there are some multithreading scenario's, but I'm not entirely sure so let's keep it by this one example. If reading this article does not change your mind and you are still putting in general exception handlers in all of your methods, then just do us all a favor and find yourself another career!

Saturday, June 10, 2006

.NET Framework 3.0 coming up!

WinFx is going to be renamed to .NET Framework 3.0. Because WinFx is based on .NET 2.0, the C# and VB compilers of version 2.0 will be redistributed. Details can be found at Jason Zander's weblog.