Exception handling has been talked about a lot over the last decade and a half. However, despite a general consensus on how to properly handle exceptions, a divide on usage continues to exist. Improper exception handling is easy to spot, easy to avoid, and is a simple code (and developer) quality metric. I know absolute rules come off as close minded or exaggerated, but as a general rule you shouldn't be using try/catch.
If an exception happens, you need to know about it. If a truly unexpected exception happens, you're better off (most of the time) crashing than letting the application continue. This is particularly true in a web application where you'll only crash 1 thread for 1 user while your site remains accessible. The best way to achieve both is let the exception go unhandled and log the exception in a global exception handler. Too often I see developer writing code which masks errors and make it impossible to build a quality system. Users complain about system instability, and developers are left scratching their heads with no leads on what the problems are.
What's even more frustrating is when framework code swallows exceptions. Take a look at this example, written by Microsoft:
private void LoadImage()
{
if (this.image != null)
{
this.image.Dispose();
}
if (source != null)
{
try
{
source = Path.Combine(Canvas.ApplicationPath, source);
image = new Bitmap(source);
IImagingFactory factory = ImagingFactory.GetImaging();
factory.CreateImageFromFile(source, out imagingImage);
}
catch{}
}
}
This is a fundamental piece of code which is part of Microsoft's UI Framework for .NET Compact Framework. The above code is buried within their framework, but through various key APIs is exposed and used extensively. This is simply horrible code. Why would they swallow any exceptions that come out of this code? The above code means that if you try to load an image "images/critical_warning.png" which doesn't exist, the application will continue to work normally. There may be cases where this is the behavior that you want, but those would be edge cases, and they should be decided at the application level, not within the framework.
The only time you should swallow exceptions (catch{..} or catch(Exception){...}) is in your global exception handler to avoid truly fundamental issues (and recursive global exception handling). You should catch specific exception (catch(XmlException){...}) when an exception isn't unexpected and you know that you can safely proceed.
A system that swallows and masks exceptions isn't a healthy system.
Posted
Mon, Jan 25 2010 10:02 AM
by
karl