Do exceptions cost performance in Java, and when does the cost actually matter?
Yes, throwing an exception costs more than an ordinary method call, but in most application code you will never notice.
Here is where the cost comes from. When an exception is thrown, the runtime walks the call stack and works out a stack trace, and it records the class name, the message, the stack frames and the cause. That work is not free, and it is done whether or not anybody ever catches the exception.
So when does the cost matter? It matters when you throw a lot of exceptions in a short time, such as inside a loop that runs a hundred thousand times. That is the pattern that turns a cheap operation into a slow one.
In ordinary application code the cost is lost in the noise. A method that throws one exception while reading a file is doing work that involves a disk or a network anyway, and the exception costs a tiny fraction of that. The advice is to never use exceptions for normal control flow, such as saying "not found" by throwing, and to never throw in a tight loop. Outside those two cases, throw the exception and do not think about it again.
public class Main {
public static void main(String[] args) {
// The normal path. No exception is made at all.
int result = parse("42");
System.out.println("parsed : " + result);
// The failure path. One exception is made, and that is fine.
try {
parse("not a number");
} catch (NumberFormatException e) {
System.out.println("failed : " + e.getMessage());
}
}
static int parse(String text) {
return Integer.parseInt(text);
}
}
The next question in this topic looks at how to measure the cost properly.