Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what ways can putting some code in try catch blocks prevent the JVM from doing optimization?

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 ?

like image 646
Geek Avatar asked Jul 19 '12 09:07

Geek


People also ask

Does try catch slow down Java?

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.

What is the advantage of using try catch block?

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.

What is the purpose of try and catch block in Java?

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.

Is it valid to place some code in between try and catch blocks?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.


1 Answers

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.

like image 112
Peter Lawrey Avatar answered Oct 15 '22 06:10

Peter Lawrey