0

A try block without any code :

try {

} catch (Exception ex) {
    // what Exception it is catching
    ex.printStackTrace();
}

The absence of any code means that throwing an exception is impossible, so why doesn't this give an "unreachable catch block" compile error?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
fastcodejava
  • 39,895
  • 28
  • 133
  • 186

3 Answers3

4

Exception includes RuntimeExceptions, which are unchecked and don't need to be declared, so Exception can always be validly caught.

I think this is an unimportant edge case.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

That's valid Java syntax. It's the same as having an empty if-block:

if (condition) {

}

... or defining an empty method:

public void empty() {

}

... or only having comments as part of the body:

try {
  // try body
} catch (Exception e) {
  // catch body
}

All of that is valid syntax, so the compiler is happy. Further, since a blank line / empty body is totally ok, no exceptions will be thrown in the body of the try block during runtime, so the code would execute just fine as well.

Hristo
  • 45,559
  • 65
  • 163
  • 230
  • 3
    I think the point is that technically `Exception` can't be thrown from no code, so there should be a "catching unthrown exception" compile error. – Bohemian Mar 03 '15 at 05:52
1

So I am assuming that your question is what Exception will get caught and the answer is none. The exception would only be caught if while running the code within the try block throws an exception. It will then check to see if that exception was caught (FYI Exception will catch all exceptions), if yes it handles it inside the catch block otherwise it causes an error. Since there is nothing in the try block the exception will never be caught because no exception can ever be thrown.

yitzih
  • 3,018
  • 3
  • 27
  • 44