Does java compiler optimize unreachable exception catch branches?

J.J. Beam :

Why is the code

void methodThrowsException() /*throws  Exception*/{
    try {
      // throw new Exception();
    } catch (Exception e) {
      throw e;
    }
}

well compiled? AFAIK compiler doesn't analyse code for can it throw an exception or not. Here obvious throw e; will never run (due to commented // throw new Exception();), but why does compiler know this?

GhostCat salutes Monica C. :

The javac compiler really doesn't do much of optimisation. But simple dead code detections and optimisations are yet possible.

In your example: the compiler can easily detect that the try block is empty. Empty try blocks can't throw, so all catch block code is essentially dead.

So the compiler could go in and simple drop the whole try/catch altogether here. Then there is nothing left that could throw an exception.

Which, when we use javap is exactly what we find in bytecode:

  void methodThrowsException();
    Code:
       0: return

And yes, the other answer is fully correct: this only works this way because you are using Exception, a more specific (checked) subclass will lead to a compiler error.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87904&siteId=1