Are Exceptions Always Errors?

It would be easy enough to assume so–but surprisingly, that’s not always the case. So the following quote from this post:

“If there’s an exception, it should be assumed that something is terribly wrong; otherwise, it wouldn’t be called an exception.”

isn’t true in all cases. In chapter 18 of Applied Microsoft .NET Framework Programming (page 402), Jeffrey Richter writes the following:

“Another common misconception is that an ‘exception’ identifies an ‘error’.”

“An exception is the violation of a programmatic interface’s implicit assumptions.”

He goes on to use a number of different examples where an thrown exception is not because of an error. Before reading Richter, I certainly believed that exceptions were errors–and implemented application logging on the basis of that belief. The exception that showed me this didn’t always apply was ThreadAbortException. This exception gets thrown if you call Response.Redirect(url). The redirect happens just fine, but an exception is still thrown. The reason? When that overload of Response.Redirect is called, execution of the page where it’s called is stopped immediately by default. This violates the assumption that a page will execute fully, but is not an error. Calling Response.Redirect(url,false) prevents ThreadAbortException from being thrown, but it also means you have to write your logic slightly differently.

The other place I’d differ with the original author (Billy McCafferty) is in his description of “swallow and forget”, which is:

} catch (Exception ex) {
AuditLogger.LogError(ex);
}

The fact that it’s logged means there’s somewhere to look to find out what exception was thrown.  I would define “swallow and forget” this way:

}catch(Exception ex){

}

Of course, if you actually catch the generic exception, FxCop would flag that as a user violation.  I’m sure McCafferty was using this as an example.