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.
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
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.
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