0

I have this code that does JDBC:

public void doMe() throws SQLException {
  try {
     ... JDBC stuff
  } finally {
     try {
        closeConnectionsAndStuff();
     } catch (Exception e) {
        logger.error(e);
        throw e;
     }
  }
}

Why does this compile? I clearly catch Exception (it's probably a SQLException but caught as an Exception none the less) and I clearly throw it.

Why will it compile without havening throws Exception as part of the method declaration?

What makes is different from this:

public void doMe() {
  throw new Exception()
}

this, of course does not compile, but I do not see the difference.

Cœur
  • 37,241
  • 25
  • 195
  • 267
mmaceachran
  • 3,178
  • 7
  • 53
  • 102
  • 4
    @JarrodRoberson OP didn't realize that the compiler can infer the thrown exception type even though the `catch` accepts any `Exception`. Seems like a valid question to me. – shmosel Jul 25 '16 at 23:24
  • 2
    @JarrodRoberson The part **specifically asked about in this question**. Not every question that asks about core language functionality is a duplicate. – chrylis -cautiouslyoptimistic- Jul 25 '16 at 23:28
  • "Why do I not have to add it to the throws part of the method declaration?" Do you mean "Why do I **have** to have it?" The code you've provided has it – Jeeter Jul 25 '16 at 23:42
  • @Jeeter Try reading it again. – shmosel Jul 25 '16 at 23:43
  • @SotiriosDelimanolis Not quite a duplicate, though I guess the answer is implied in that question. – shmosel Jul 25 '16 at 23:50
  • @SotiriosDelimanolis This is not a duplicate as it deals with the throws declaration and not the catch block. – mmaceachran Jul 26 '16 at 17:24
  • Forget about the question and read the answers. [This one specifically addresses your issue.](http://stackoverflow.com/a/35184196/438154) Your method is already declared to `throws SQLException`, so that's taken care of. The signature of `closeConnectionsAndStuff()` probably doesn't have any `throws` for checked exception so the compiler can tell that anything caught from that invocation can only be an unchecked exception. So anything in that `Exception` parameter will be unchecked (or `SQLException` which you've already handled). You don't need a `throws` for unchecked exceptions. – Sotirios Delimanolis Jul 26 '16 at 17:28
  • Quoting from that answer I linked: _This means that the compiler can detect that the only possible exception types thrown in test are Errors or RuntimeExceptions, neither of which need to be caught. When you throw e;, it can tell, even when the static type is Exception, that it doesn't need to be declared or re-caught._ – Sotirios Delimanolis Jul 26 '16 at 17:28

0 Answers0