Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: can't rethrow exception: Unhandled exception type Exception

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?

like image 233
opensas Avatar asked Feb 29 '12 05:02

opensas


2 Answers

I think there are various things to mention here:

  1. You either want 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.
  2. It's a Don't to catch an exception, log it and rethrow it. Why? Because a potential caller of your method does not know that you are already logging it, and migh log it as well. Either throw an exception (in which case the caller has to deal with it) or catch it and handle it (log it).
  3. Note that throwing 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.
  4. Moreover, if you throw 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.
like image 165
quaylar Avatar answered Sep 22 '22 12:09

quaylar


Your doJobWithResult method needs to declare that it can throw Exception:

public Boolean doJobWithResult() {

becomes

public Boolean doJobWithResult() throws Exception {
like image 27
Paul Jowett Avatar answered Sep 22 '22 12:09

Paul Jowett