Is returning null after exception is caught bad design

woolagaroo picture woolagaroo · Jan 30, 2010 · Viewed 13.4k times · Source

I always come across the same problem that when an exception is caught in a function that has a non-void return value I don't know what to return. The following code snippet illustrates my problem.

public Object getObject(){
  try{
    ...
    return object;
  }
  catch(Exception e){
    //I have to return something here but what??
    return null; // is this a bad design??
  }
}

So my questions are:

  • Is return null bad design?
  • If so what is seen as a cleaner solution??

thanks.

Answer

duffymo picture duffymo · Jan 30, 2010

I would say don't catch the exception if you really can't handle it. And logging isn't considered handling an error. Better to bubble it up to someone who can by throwing the exception.

If you must return a value, and null is the only sensible thing, there's nothing wrong with that. Just document it and make it clear to users what ought to be done. Have a unit test that shows the exception being thrown so developers coming after you can see what the accepted idiom needs to be. It'll also test to make sure that your code throws the exception when it should.