From Exceptions chapter in Effective Java:
Placing code inside a try-catch block inhibits certain optimizations that modern JVM implementations might otherwise perform
Why and how does a try-catch block prevent optimization by JVMs ?
From Exceptions chapter in Effective Java:
Placing code inside a try-catch block inhibits certain optimizations that modern JVM implementations might otherwise perform
Why and how does a try-catch block prevent optimization by JVMs ?
The JVM might not combine or re-order operations inside the try/catch block with those outside the try/catch block. Every layer of complexity makes optimisation harder. If its a relatively rare case, it might not be handled by the JVM which will, if in doubt, choose correctness rather than optimal code.
One of the reasons "why" is that exceptions and exception handling are assumed to be exceptional; i.e. code that is rarely executed. It follows that time spent by the JIT compiler on optimizing exception handlers is going to have little benefit to the overall performance.
The JIT compiler's optimizer has to balance the performance benefits of optimizations that are effective against the costs of optimizing. The latter include:
There may also be technical reasons that inhibit optimization of exception handlers. For instance, it may not be easy (or even possible) for the optimizer to figure out where the flow of control "came from". Hence, optimization that are based on knowing that (e.g. caching stuff in registers, hoisting common subexpressions, ...) can't be performed.
Check the following link:
I guess exceptions are Java objects and these objects need to be created. Creating an object is a costly operation. So use exceptions only for handling errors and not to control flow.