dagblog.
← Archive

What throwing an exception actually does to Java performance


A long time ago, I read or perhaps heard that throwing an exception
 is expensive and slows things down. Yesterday I found a class in the tools for one of our projects 
 that was used to get the current execution context. The class has a static method 
 that throws an exception, processes its stack trace, and returns the name of the class and method

that called it.

Since the class that looks up the context is called fairly often, I thought I’d test the old rule of thumb

and measure how fast a program runs when it throws exceptions.

How I measured it

I set up an object called Dummy, with a static method that throws an

exception. The method also calculates pi, just to simulate a real operation.

public class Dummy {	
public static void doSomethingFishy(boolean withException){
if(withException){
try{
throw new Exception();
}catch(Exception e){
//do nothing
}
}
double currPi = 0;
double i = 1;
do {
currPi += 4/i - 4/(i+2);
i+=4;
} while (Math.abs(Math.PI - currPi) > 1E-7);
}
}

I also set up a thread that calls the static method doSomethingFishy and

a loop that creates and starts a specified number of threads.

.
.
.
boolean exception = Boolean.valueOf(args[0]).booleanValue();
int threadCount = Integer.parseInt(args[1]);
for(int foo = 0; foo < threadCount; foo++){
new Thread(new MyThread(exception)).start();
}
.
.
.
class MyThread implements Runnable{
private boolean exception = true;

public MyThread(boolean exception){
this.exception = exception;
}

public void run() {
Dummy.doSomethingFishy(exception);
}
}
The exception variable controls whether the exception is thrown, and threadCount controls how many threads start.

Measurements

I ran three measurements each with and without exceptions, using 100 threads. I measured
the test’s runtime in seconds using the operating system function
that returns the current time.
With exception (s)  Without exception (s)    15,15  15,12     15,16  15,15     15,17  15,23
The results suggest that throwing an exception had little or no effect on the program’s speed. I tried varying the number of threads and saw very little change in the results, so I’d say the thread count makes only a minor difference.

An important caveat

The aim of this measurement was to find out how much throwing an exception affects program speed. Even though
the effect turned out to be negligible, exceptions should signal exceptional situations. Ordinary program flow and looking up the current context on each HTTP request hardly qualify.
The test program  includes binaries and source files as well as a Windows batch file. The arguments are true|false for with or without exceptions and the number of threads, for example run.bat true 10.

Medium version

Related articles

Related CZ Podcast episodes