The question says it all. Although the hit is not highly significant (I measured it to be between 1.5x to 2x slower), there's no difference between the byte code with try-catch and the byte code without it. So what makes it generally slower?
Pl. note that the question is not about overhead of throwing an exception, but of entering/leaving a try block.
EDIT: here's the code (run on Hotspot 1.6.0_31 server)
static void tryCatch()
{
int i = 0;
long l1 = getTime();
for(int j = 0; j < 100000; j++)
{
try
{
i++;
}
catch(Exception e)
{
}
}
long l2 = getTime();
System.out.println("with try-catch: " + (l2 - l1) + ": " + i);
}
static void noTryCatch()
{
int i = 0;
long l1 = getTime();
for(int j = 0; j < 100000; j++)
{
i++;
}
long l2 = getTime();
System.out.println("w/o try-catch: " + (l2 - l1) + ": " + i);
}
static long getTime()
{
return System.nanoTime();
}
My microbenchmark for another question showed there is no significant difference between using/not using a try-catch block, with or without throwing exception in a block or not.
Since you have a micro-benchmark its is more likely you are testing how confusing the try/catch block is to the JVM compiler. For example, the JVM can be smart enough to change
into
using the try/catch block may prevent the more aggresive optimisations, but might not make any difference for a more realistic block of code.
In any case I would normally change something like
.