Exception Swallowing

Exceptions are a fundamental part of a program. For example, if you creating, editing, and closing a database, an exception is needed in case anything goes wrong. However, exception handling can go awry when the exception is swallowed.

Consider the following snippet :

try{
    db.open()
    db.modifySomething();
    db.close();
}
catch(Exception ex) {
   //exception is swallowed
}

If the database throws an exception anytime between opening the database, and closing the database, then the database will simply not close. This can cause huge problems over time, as dozens of unclosed databases would exist at the same time.

The goal of exceptions isn’t to make your life more difficult. The goal is to help you, the programmer, catch errors in your code, and to give you a stack trace so that you know where your code has a problem.

Consider this scenario :

A car drives down a road, but the engine catches on fire. The man inside the car, instead of getting out, opts to continue driving and dies after the car explodes.

Or, the more logical scenario :

A car drives down a road, but the engine catches on fire. The man realizes this, so he gets out of the car immediately. He sees there is a gas leak. The car explodes, but the man survives.

The first scenario is a prime example of what would happen if the exception was swallowed. Not only does the man not know why the engine caught on fire, but he also died.

However, the second scenario shows what would happen if the exception was handled. First, the man escaped safely from the car. In addition he also knows why the engine caught on fire. Similarly, a programmer who properly handles exceptions can find out where the program went wrong, as well as why it went wrong.

Here’s a general rule of thumb :
Fail fast, fix it fast.

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s