Exception handling is expensive, and it is 66x+ slower than compared to regular function call 🤯
I was digging deeper into the JVM to understand the cost of try-catch, and there are some interesting things that I found. First, the one I mentioned - 66x slower, but what if the exception never occurs, does it still impact the performance?
Turns out, even the “harmless” try block itself isn’t truly free. try/catch has some impact on performance as it prevents the JVM from doing some optimizations. JVM treats any code within a try block as potentially exception-throwing, preventing some optimizations like
- code reordering across try block boundaries
- method inlining optimizations
- dead code elimination assumptions
Also, what makes handling exceptions expensive is that when they occur, the runtime does two things
- captures the complete call stack
- JVM searches up the call stack for appropriate handlers
Now, if the catch block for the exception is located in the same method, the impact is not so bad. However, the further down the handler is in the call stack, the longer it takes the JVM to find the exception handler, and hence the greater the penalty.
So, the bottom line is - you should use a try/catch block only for error conditions, but never for simply controlling the program flow.
Hope this helps.