boolean returns false if the method execution fails, so that an error can be shown to user
This is a clear reason for the method to throw an exception. It is why the exception mechanism exists in the first place. Best practice is to use exceptions for these types of circumstances, not boolean signals.
Anytime you follow this kind of pattern, you suffer in several ways
- The caller cannot be sure what really happened. Was there a communication failure? Was the data corrupted? There is no way to tell when you return a simple "FAILED" signal.
- Because the caller cannot know what happened, you take away options for the caller. Maybe the caller could do something in certain error cases.
- You increase the potential for data errors. Again, since the caller cannot know why it failed, the caller may make assumptions about why it failed and continue in cases when the entire program should halt. If the program continues, it may decide to process invalid data when it really should stop.
I highly recommend reading the sections on exception handling in Effective Java. Basically, if you can't do anything meaningful with an Exception in your method, you should allow it to pass up the stack. In the worst case scenario, the API you reference throws a generic checked exception, giving you one of three choices (EDIT: Changed to void return type because the boolean return type no longer has any meaning -- you either succeed or throw an exception)
-Create your own.
// "MyFatalException" would be a checked Exception public void saveData() throws MyFatalException{ try{ // ... do stuff that throws Exception }catch(Exception e){ throw new MyFatalException("Unable to save Data due to a general exception"+ " thrown by foo.bar()", e); } }
-Throw an existing type (my preference is for subclasses of RuntimeException)
public void saveData() throws IllegalStateException{ try{ // ... do stuff that throws Exception }catch(Exception e){ throw new IllegalStateException("Unable to save Data due to a general exception"+ " thrown by foo.bar()", e); }
-Declare to throw a generic Exception and let it pass up (I do NOT recommend this, but you'll see many developers who do this)
public void saveData() throws Exception{ // no try/catch needed. Just make the call }
saveData