Repeated Throwing Exception Exception?

Consider the following code:

static void main(String[] args) {
  try {
  } catch (Exception e) {
    throw e;
  }
}

This code compiles without adding throws Exceptionto the method signature. (He behaves similarly Throwableinstead Exception).

I understand why this can be safely run, since Exceptionit cannot be really selected in the block try, so a checked exception cannot be excluded; I am interested to know where this behavior is indicated.

It is not easy that is throw enever achieved: the following code also compiles:

static void stillCompilesWithThrownUncheckedException() {
  try {
    throw new NullPointerException();
  } catch (Exception e) {
    throw e;
  }
}

But if you throw a checked exception, it will not compile as I expect:

static void doesNotCompileWithThrownCheckedException() {
  try {
    throw new Exception();
  } catch (Exception e) {
    throw e;  // error: unreported exception Exception; must be caught or declared to be thrown
  }
}

The JLS Sec 11.2.2 states:

A throw (§14.18), E , E , .

, throw e Exception, e Exception. , JLS Sec 11.2.3:

, E, E - , E , throws .

. ?


: , , : throw e; .

JLS Sec 14.21:

  • catch C , :

    • C Exception, Exception, throw try , C. ( , , , .)

      . § 15.6 .

    • try catch A, C A.

( Exception, catch), "". , try .

+4
1

, 11.2.2 :

A throw, catch C, E iff:

  • E - , try try, C;
  • ...

, throw e; " " , try-block ", try-.

, try "can throw" . " " NullPointerException, catch " " , try-block, "catch-block" NullPointerException.

try-block "can throw" java.lang.Exception , catch-block " throw" java.lang.Exception, java.lang.Exception , .

+1

Source: https://habr.com/ru/post/1658507/


All Articles