In Java, using throw/catch as a part of logic when there’s not actually an error is generally a bad idea (in part) because throwing and catching an exception is expensive, and doing it many times in a loop is usually far slower than other control structures which don’t involve throwing exceptions.
My question is, is the cost incurred in the throw/catch itself, or when creating the Exception object (since it gets a lot of runtime information including the execution stack)?
In other words, if I do
Exception e = new Exception();
but don’t throw it, is that most of the cost of throwing, or is the throw + catch handling what’s costly?
I’m not asking whether putting code in a try/catch block adds to the cost of executing that code, I’m asking whether catching the Exception is the expensive part, or creating (calling the constructor for) the Exception is the expensive part.
Another way of asking this is, if I made one instance of Exception and threw and caught it over and over, would that be significantly faster than creating a new Exception every time I throw?