15

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?

10 Answers 10

8

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.
2
  • all answers were pretty useful, I think this one also gives a few hints about how to deal with exceptions...
    – opensas
    Feb 29, 2012 at 13:45
  • Most of this is spot on, but the only counter point I want to raise is with #2. It highly depends on your application structure, but in the case of building a REST API, a multi-tiered approach of layering exception handling can work well. For example, you can handle the exception when it is thrown with logging then throw a new wrapper exception as suggested in #3. Something like RecoverableClientException and UnrecoverableClientException can let calling code know how it can proceed. Wrappers can also help decide what kind of response and HTTP status code to send back to the client. Aug 29, 2019 at 17:38
8

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

public Boolean doJobWithResult() {

becomes

public Boolean doJobWithResult() throws Exception {
6

You can throw the same exception if you add throws Exception to your method signature. Otherwise you can throw a RuntimeException.

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 new RuntimeException(ex); 
    } 
    return result; 
} 

In such a case, you won't need to indicate that public Boolean doJobWithResult() throws something but make sure you handle it properly later on (catch or expect your thread to stop... it's a RuntimeException afterall).

3

Since Exception is checked, an alternative to catching the Exception is to declare your method as throwing it:

public Boolean doJobWithResult() throws Exception {
    // ...
}
1
  • Simple and straight forward answer. A 10 point bonus from me :) Dec 19, 2019 at 7:32
3

If doJobWithResult doesn't have to handle the exception, then remove the catch block and add "throws Exception" to the method signature. The exception logging can be done in the class/method that have to deal with the Exception in a corresponding try/catch block.

2

There is no need to set the result as false in the catch block, as the value won't be returned(as we are throwing an exception).

Your method should also declare that it throws an exception and so the client will be forced to handle it.

Also consider using a more specific exception which will be thrown in this particular case.

1

Add throws Exception to your method. You also don't need to add result = false; in your catch block.

1

I think the way you handle this exception is really appropriate if any failure of feed.fetchContents() method cannot be recovered. (Idea is better to halt rather than continuing) Apart from that I would suggest you to use more specific exception hierarchy.

And another thing I got from effective java book is if you write such a method you must document with @throw (in comments) with the reason.

0

You could throw an unchecked exception

 Logger.info("fetching feed(%d) failed", feedId);
 throw new RuntimeException(ex);
0

I spent the last hour looking for it since not even the Complete Reference book mentions this explicitly: unhandled throw ThrowableInstance works only with unchecked exceptions.. And only runtime exceptions are unchecked. By unhandled I mean something like this:

class ThrowDemo {
  static void demoproc() {
    try {
      throw new NullPointerException("demo");
    } catch(NullPointerException e) {
      System.out.println("Caught inside demoproc.");
      throw e; // re-throw the exception
    }
  }

  public static void main(String args[]) {
    try {
      demoproc();
    } catch(NullPointerException e) {
      System.out.println("Recaught: " + e);
    }
  }
}

This example is taken verbatim from the Complete Reference book (9th edition).

The first throw statement i.e throw new NullPointerException("demo"); is handled by the following catch block, but the second throw statement i.e. throw e; is unhandled by the demoproc() method. Now this works here and the above code compiles successfully because NullPointerException is a runtime/ unchecked exception. If the e instance were a checked exception or even an Exception class instance then you'd get an error saying the exception e is unhandled and you'd either have to handle it within demoproc() or you'd have to explicitly declare that demoproc() throws an exception using throws in the method signature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.