Question: Is exception handling in Java actually slow?
Conventional wisdom, as well as a lot of Google results, says that exceptional logic shouldn\'t be used for n
FYI, I extended the experiment that Mecki did:
method1 took 1733 ms, result was 2
method2 took 1248 ms, result was 2
method3 took 83997 ms, result was 2
method4 took 1692 ms, result was 2
method5 took 60946 ms, result was 2
method6 took 25746 ms, result was 2
The first 3 are the same as Mecki's (my laptop is obviously slower).
method4 is identical to method3 except that it creates a new Integer(1)
rather than doing throw new Exception()
.
method5 is like method3 except that it creates the new Exception()
without throwing it.
method6 is like method3 except that it throws a pre-created exception (an instance variable) rather than creating a new one.
In Java much of the expense of throwing an exception is the time spent gathering the stack trace, which occurs when the exception object is created. The actual cost of throwing the exception, while large, is considerably less than the cost of creating the exception.