It was always told me that Java exception handling is quite expensive.
I’m asking if is it a good practice creating an exception instance of a specific type at the beginning of the program and without creating a new one, throwing always the same exception object.
I just want to make an example. Common code:
if (!checkSomething(myObject))
throw new CustomException("your object is invalid");
alternative:
static CustomException MYEXP = new CustomException("your object is invalid");
//somewhere else
if (!checkSomething(myObject))
throw MYEXP;
Of course, I’m doing some assumptions here:
MyCustomExceptionhas no parameters- client code, whenever is a good practice or not, is heavlily based on exception handling and refactoring is not an option.
So questions are:
- Is this a good practice?
- Does this damage some JVM mechanism?
- If 1 is yes, there is the possibility of a performance gain? (I think not, but not sure)
- If 1 and 3 are yes, why is not sponsored as practice?
- If 1 is no, why Martin Odersky told in his introduction to Scala that this is how Scala works in some cases? (At minute 28.30 he tolds that break is implemented has throwing an exception, audience says that this is time consuming and he replies that exception is not created every time)Fosdem 2009
I hope this is not a idle/stupid question, I’m curious about this. I think that real cost in exception handling is handling and not creation.
edit
Added reference of precise discussion on FOSDEM presentation
disclaimer: none of my code works like proposed and I have no intention to manage exception like this, I’m just doing a “what-if” question and this curiosity is generated from the affermation that video. I thought: if it’s done in Scala, why is not in Java?
No, don’t do that. The expensive part is not handling the exception, it is generating the stacktrace. Unfortunately the stacktrace is also the useful part. If you throw a saved exception you will be passing on a misleading stacktrace.
It could be that within the implementation of Scala there are situations where it makes sense to do this. (Maybe they are doing something recursive and want to generate an exception object upfront so in case they run out of memory they can still produce an exception.) They also have a lot of information about what they’re doing so they have a better chance of getting it right. But optimizations made by JVM language implementors are a very special case.
So you wouldn’t be breaking anything, unless you think providing misleading information constitutes breakage. It seems like a big risk to me.
Trying out Thomas Eding’s suggestion for how to create an exception with no stacktrace seems to work:
Also check out the JLS: