I’ve read pretty often, that using try-catch is quite slow compared to normal code.
Now I wonder if the number of caught exceptions affects the performance of the code or not.
So is
try{
...
}
catch(StrangeException e){
...
}
slower than
try{
...
}
catch(StrangeException e){
...
}
catch(MysteriousException e){
...
}
catch(FrighteningException e){
...
}
?
Of course I’m only referring to the code in the try-clause and if no exception is caught.
The cost of a try / catch block is essentially zero if no exceptions are actually thrown. The number of catch clauses makes no difference.
The cost of exceptions occurs only when they actually get thrown:
Constructing the exception object is very expensive, because of the cost of the
fillInStackTrace()step. This has to create and initialize a data structure containing key details of all frames on the current thread stack. In the worst case, there could be thousands of them.Throwing and catching exceptions is a bit expensive. In the worst case, the JVM needs to do the equivalent of an
instanceoffor eachcatchclause of each try / catch block. This is where having lots ofcatchclauses could make a difference to performance.