We are making an Excel-like system. When we open a document and found unsupported functions we threw exception. We just support small subset of excel functions, this could happen frequently. The problem is when there are a lot of cells that contains unsupported functions, lots and lots of exception instances are created. And creating those many exception instances consumes unignorable amount of time.
We don't have any special properties within the exception class. What we need to know is the fact that the exception is thrown. We just found that the error has occurred and mark the cell as error.
So we decided to share one exception instance and throw it whenever needed. The exception instance can be thrown by multiple threads. I suspect that the stack trace could be corrupted, however, we don't see it. We just catch the exception, and mark the corresponding cell as error.
My question is: In this situation, is it safe to share exception instance? Well, I read the following article: Java: is Exception class thread-safe? But the context seems to be different.
Thank you for reading this long question and response in advance.
You should handle the exception at the lowest possible level. If method can't handle the exception properly you should throw it.
The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.
No. Throwing the same instance of Exception from multiple places in your code (not counting rethrows!) is not recommended. An Exception contains more then just it's message - it contains valuable information for debugging such as the stack trace.
[...] is it safe to share exception instance?
Yes, if you're careful.
If you're not careful, the getStackTrace
for instance may get messed up. Either make sure each thread has it's own exception object, or override getStackTrace
and return an empty array.
(The JVM actually reuses exception instances in some cases. If it runs out of memory, it will reuse a preallocated OutOfMemoryError
instead of trying to create a new one for instance. In this case the getStackTrace
returns an empty array.)
Related question:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With