What costs for sure less time for execution between the two options:
A:
if(something!=null){
...
}else{
//log
}
or:
B:
try{
something.getField();...
}catch(Exception e){
//log
}
What costs for sure less time for execution between the two options:
A:
if(something!=null){
...
}else{
//log
}
or:
B:
try{
something.getField();...
}catch(Exception e){
//log
}
if
definitely.
Throwing an exception is a costly operation and this is not the purpose of Exception
.
The purpose of Exception is to catch exceptional condition that may arise at runtime but you shouldn't code to generate exception to make that decision.
Without even having to benchmark: Exception are ALWAYS way more expensive than programming defensively and using ifs as null-guard etc. Exceptions are always more expensive (several orders of magnitude), because the stack trace has to be generated.
Relevant SO question with benchmark: How slow are Java exceptions?
If emits a single branch. Throwing an exception "unrolls" the stack, which takes much longer.