wulfgarpro
wulfgarpro

Reputation: 6934

How to handle localized exceptions?

I always seem to come to a cross road where I don't exactly know how to handle an exception without re-throwing to the caller.

Is there a better way to handle the below situation?

private DataHandler retrieveFromGridFS(ObjectId id) throws IOException
{
    GridFS gridFS = new GridFS(getDBReference());        
    GridFSDBFile out = gridFS.find(id);

    File temp = File.createTempFile(
            (String)out.getMetaData().get("productName"), 
            (String)out.getMetaData().get("productType"));

    out.writeTo(temp);

    return new DataHandler(new FileDataSource(temp));        
}

The above private method can throw an IOException.

Making use of this method like so:

public DataHandler retrieveProduct(String productId) throws IOException
{
    ObjectId id = new ObjectId(productId);
    DataHandler handler = null;

    try
    {
        handler = retrieveFromGridFS(id);
    }
    catch(IOException ex)
    {
        logger.error(ex);
        throw new IOException("A problem occurred retrieving product.");
    }

    return handler;
}

I'm forced to re-throw so that I don't risk returning null.

Upvotes: 2

Views: 476

Answers (3)

What? Looks to me like retrieveProduct is just a convenience function to do whatever retrieveFromGridFS does but with a String as an identifier instead of an ObjectId. So shouldn't the set of exceptions it can raise just be the same as that of retrieveFromGridFS?

Upvotes: 0

seand
seand

Reputation: 5286

Generally speaking, catch the exception if you can respond to the event that occurred. Ex. let's say you have code to retry connections upon failure. Then you might have a loop which catches IOException and retries x times. The caller above doesn't care about the underlying failures.

When an exception occurs that you can't handle, you don't wouldn't it. Essentially you're passing the buck.

Lately I've tended to avoid rethrowing exceptions as others exc objects in most cases. I've found through experience it doesn't really add value most of the time.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160191

It totally depends.

For one thing, do you really want to percolate an IOException to the upper layers, or do you want to encapsulate the various exceptions that can occur at the lower layers in an application-specific exception?

Do you need to be able to recover from this exception? If not, is a RuntimeException more appropriate? (Even if you do need the exception to be recoverable, are you operating in an environment that provides for declarative exception handling at a high level?)

Would it make more sense to use a NullObject pattern to avoid returning a null?

(Etc. :)

Upvotes: 2

Related Questions