I'd like to catch an exception, log it, set a flag, and the rethrow the same exception
I have this code:
public Boolean doJobWithResult() {
boolean result = true;
final Feed feed = Feed.findById(feedId);
try {
feed.fetchContents();
} catch (Exception ex) {
result = false;
Logger.info("fetching feed(%d) failed", feedId);
throw ex;
}
return result;
}
But eclipse complains at throw ex, telling that "Unhandled exception type Exception", and suggests me to add a try-catch block around it.
In fact, I want the process calling this method to handle the exception, and not handle it myself... I just want to return true if everything goes ok, and log it if there's an exception
On the other hand, I can wrap the exception inside another exception, but I can't throw the same one..
any idea?
I think there are various things to mention here:
doJobWithResult()
to return true on success and false on failure, or return nothing on success and throw an exception on failure.
Both at the same time is not possible. In the first case, catch the Exception, log it and return false, in the second case change your signature to return void
and throw an exception and handle it in the caller.Exception
does not give the caller of your method any clue about what might potentially go wrong in your method, it's always better to throw more specific exceptions, or to wrap an exception in a user-defined one and rethrow it.Exception
, a caller might be tempted to catch Exception
without noticing that this will also catch every RuntimeException (since its derived from Exception
), which might not be desired behavior.Your doJobWithResult method needs to declare that it can throw Exception:
public Boolean doJobWithResult() {
becomes
public Boolean doJobWithResult() throws Exception {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With