Teaser Image

qnoid

Markos Charatzas - Edinburgh, UK




/**
 * You are asking for trouble here
 */
public void buyMuffin(LocalStore localStore, Flavour flavour)
{
    try
    {
        localStore.buyMuffin(flavour);
    }
    catch(MuffinNotFoundException e)
    {
        System.out.println("Pissed!");
    }
        
    System.out.println("Good bye!");
}

/**
 * Not my problem I don't have any money!
 * (InsufficientFundsException not handled)
 * You aren't being polite.
 */
public void buyMuffin(LocalStore localStore, Flavour flavour)
{
    try
    {
        localStore.buyMuffin(flavour);
    }
    catch(MuffinNotFoundException e)
    {
        System.out.println("Pissed!");
    }

    System.out.println("Good bye!");
}

/**
 * I don't give a damn! Still have to be polite though.
 */
public void buyMuffin(LocalStore localStore, Flavour flavour)
{
    try
    {
        localStore.buyMuffin(flavour);
    }
    catch(MuffinNotFoundException e)
    {
        System.out.println("Pissed!");
    }
    finally
    {
        System.out.println("Good bye!");
    }
}

/**
 * Just want my muffin
 */
public void buyMuffin(LocalStore localStore, Flavour flavour)
{
    try
    {
        localStore.buyMuffin(flavour);
    }
    finally
    {
        System.out.println("Good bye!");
    }
}

There has been a lot of debate about exceptions and their usage in the Java world. This post is not about it.

A foreword on what exceptions really are in case you are still confused.

Consider yourself going to your local store to buy a muffin (an addict here).

Now I prefer a chocolate one but the local store might not have one. So I walk in, go to the muffins section and... there is none! Something unexpected happened (hint an Exception). Yeah I'm pissed but I still have to be polite and say goodbye on my way out.

Now the only way to ensure that; is the 'finally' clause in a try/catch block. Here is why.

Without a 'finally' this might very well work. You do handle the exception right there and you still get to say "Good bye!" at the end. There are 2 things to consider though.

  • the LocalStore#buyMuffin(Flavour) method might very well change (especially if it's third party code) introducing a new exception to the mix (InsufficientFundsException since people were just buying muffins without having enough money to pay). You aren't being polite anymore.
  • you may not be responsible for handling the situation of not having enough money to buy a muffin. Your dad/employer/clients are. (in the "real world" an example would be to have a common class to log the exceptions)

Now in both cases not having a 'finally' clause will simply break your code sooner or later. (Picture this with database connections and you have a serious leak there)

Disclaimer Take the advice. Not the code. It's just an example.