Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to share exception instance

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.

like image 615
ntalbs Avatar asked Jul 13 '12 15:07

ntalbs


People also ask

Where should exceptions be handled?

You should handle the exception at the lowest possible level. If method can't handle the exception properly you should throw it.

Is throwing exception good practice?

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.

Can we Rethrow same exception multiple times in Java?

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.


1 Answers

[...] 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:

  • How can a preallocated OutOfMemoryError truthfully implement Throwable.getStackTrace if thrown twice?
like image 109
aioobe Avatar answered Sep 22 '22 16:09

aioobe