-1

I'm doing some code cleaning, removing catch Throwable and catch Exception, but I noticed some odd behavior in Eclipse.

In this piece of code, Eclipse will mark the IOException path as unreachable, which is correct, but not the Exception path. Isn't the Exception path equally unreachable? java.lang.Exception is a checked Exception? Right?

    try {
        log.info("Some message");
    } catch (IOException e) {
        log.debug(e.getMessage(), e);
    } catch (Exception e) {
        log.info(e.getMessage(), e);
    }
pagerbak
  • 93
  • 1
  • 1
  • 6

2 Answers2

2

java.lang.Exception is the parent class of all the Exceptions (although not all the Throwables!). As it is also the parent of java.lang.RuntimeException, you can always attempt to catch it, as any piece of code may throw a RuntimeException.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

The Exception catch block is not unreachable, because Exception also includes all unchecked exceptions (exceptions which extend RuntimeException, which is a subclass of Exception).

The difference between checked and unchecked exceptions is that for the former, a method is required to either catch and handle the exception, or declare that it might throw the exception with a throws clause; for the latter (unchecked) this requirement doesn't exist, a method can throw an unchecked exception even if it doesn't declare that it might throw it. (See The Catch or Specify Requirement in Oracle's Java Tutorials for more details).

To determine if a catch block is unreachable, the compiler only looks at the checked exceptions that might happen in the code in the try block.

Since your catch (Exception e) also includes catching unchecked exceptions, it's always allowed to have this block.

Jesper
  • 202,709
  • 46
  • 318
  • 350