Advertisements

Exceptions


What are your best practices when it comes to exceptions?

Do you always log them?

In the past, I have stuck with the advice of Joshua Bloch.  Exceptions are for exceptional situations.  It is Item 39 in his great work Effective Java: Programming Language Guide. If it’s not exceptional and you expect the condition to happen sometimes; use an if.. else block.

Also, stick to the out-of-the-box exceptions as much as possible and create your own exceptions only when you need to.

Exceptions are a great way to communicate the contract of a method if you’re writing an API or client library.  But if you’re writing a code in a small team, does it really help to throw exceptions all over the place?

I think it does in certain situations.  For example, if your team is writing a layered architecture app; then each layer would benefit from throwing exceptions to the layer above it that depends on it.  Within the layer I don’t think it buys you much.  But from the data layer to the business logic layer and then to the presentation layer; a lot of meaning can be translated through exceptions.  Plus, these layers are usually written by different people and in parallel.  Exceptions help the other developers know what to expect from the methods they call in these lower layers.

Please comment with your exception best practices!

Advertisements

About Leonard Woody
Software Engineer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: