Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cost of try catch blocks?

How much better is:

 if (condition) {
  try {
   //something
  } catch(SomeEx ex) {}
 }

instead of this:

 try {
   if (condition) {
     //something
   }
 } catch(SomeEx ex) {}

What actually JVM do when I enter try block ?

EDIT: I don't want to know that in second example always go in to try... Please answer the question.

like image 771
Smolda Avatar asked Jul 31 '13 09:07

Smolda


2 Answers

Execution wise at run time, as long as there is no exception, try does not cost you anything. It only costs run time as soon as an exception occurs. And in that situation it is much slower that an if evaluation.

In the JVM spec, you see that there is no extra byte code generated on the execution path: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12

like image 185
FrankPl Avatar answered Oct 27 '22 07:10

FrankPl


try {if (condition) {...}} catch(SomeEx ex) {}

Here you handled the exception if it is arised condition of if also if arised inside if-block.

if (condition) {try {...} catch(SomeEx ex) {}}

Here you handle exception if is arised only inside the if-block. If something goes wrong in if condition then it will not be handled.

So it is depends upon the actual senario.

like image 3
Subhrajyoti Majumder Avatar answered Oct 27 '22 09:10

Subhrajyoti Majumder