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 ?
In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.
One of the benefits of try/catch is its ability to display your own custom-created error. This is called (throw error) . In situations where you don't want this ugly thing that JavaScript displays, you can throw your error (an exception) with the use of the throw statement.
Java try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With