Both methods are fine, the important part is that in the end it does not matter as long as the behavior is documented.
I would also clean your code up a little:
/**
* Creates a new MyObject, returns null on failure and logs the exception.
* @return A new MyObject or null on failure.
*/
public MyObject foo() {
try {
MyObject myObject = new MyObject();
myObject.manipualteData();
myObject.reticulateSplines();
return myObject;
} catch (DontCatchGenericExceptions ex) {
LOGGER.log(Level.SEVER, "Creation of MyObject failed!", ex);
}
return null;
}
If you don't want to return null
(because, let's face it, sometimes it sucks) you can also throw the exception and let it be handled above you:
/**
* Creates a new MyObject.
* @return A new MyObject.
* @throws YourCustomException If the creation of MyObject failed.
*/
public MyObject foo() throws YourCustomException {
MyObject myObject = new MyObject();
myObject.manipualteData();
myObject.reticulateSplines();
return myObject;
}
If you want to return an Object and handle the exception yourself, I'd suggest to expand the Object by a field which does allow the user to check for readiness of the returned Object:
public class MyObject {
private boolean ready = false;
public boolean isReady() {
return ready;
}
public void finishInitialization() {
if(ready) {
// It was called a second time,
// maybe you want to throw an exception?
}
ready = true;
}
}
/**
* Creates a new MyObject.
* @return A new MyObject.
*/
public MyObject foo() {
MyObject myObject = new MyObject();
try {
myObject.manipualteData();
myObject.reticulateSplines();
myObject.finishInitialization();
return myObject;
} catch (DontCatchGenericExceptions ex) {
LOGGER.log(Level.SEVER, "Creation of MyObject failed!", ex);
}
return myObject;
}
This way the user of your function/object can easily check if the returned Object was actually usable:
MyObject myObject = foo();
if(myObject.isReady()) {
// Do something here with myObject
} else {
// This sucks! The object-creation failed.
}
Though, this only avoids the null-check, but it's basically the same code as if you'd return null
directly.
Also be aware that my little documentation here is not the best example on how to do JavaDoc documentation. It needs to be better worded and extended.
try { return new MyObj(); } catch (Exception e) { return null; }
– luiscubal Aug 26 '13 at 14:08foo()
? If all you can do about it is log a message, it might make sense to havefoo()
throw an exception. This way the caller decides what to do and doesn't have to check fornull
. – unholysampler Aug 26 '13 at 17:44