Don't catch OutOfMemoryError
See original GitHub issueGson currently catches OutOfMemoryError
s at two places and wraps them inside JsonParseException
:
https://github.com/google/gson/blob/c5a3f21fbad3828deba1deb88168e1f76829f807/gson/src/main/java/com/google/gson/JsonParser.java#L88-L89
https://github.com/google/gson/blob/b75e1bbc7915f409ba0254fcc92c71ed6798e69b/gson/src/main/java/com/google/gson/JsonStreamParser.java#L90-L91
This is bad practice because Gson is not necessarily the cause for this error and wrapping it inside an Exception
subclass prevents the caller from noticing the OutOfMemoryError
until later.
Edit: Catching OutOfMemoryError
might be desired to protect about malicious JSON data, see also https://github.com/google/gson/pull/1912#issuecomment-1130767871. However, it appears OutOfMemoryError
is not caught consistently everywhere.
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (3 by maintainers)
Top GitHub Comments
@wind57 just to be clear: I didn’t design it, but I’m trying to reconstruct the rationale behind the design choice and trying to figure out why several errors (OOM is just one of them) are caught right there, despite most sources recommend never catch these but log them at the very top level (or just let the JVM to crash). Perhaps catching the OOM error might be fine when trying to allocate too lengthy memory blocks (like arrays I was thinking of above or any other objects that may require such arrays under the hood (huge bitmaps/images, huge strings, etc: https://stackoverflow.com/questions/2679330/catching-java-lang-outofmemoryerror)) and not work fine when trying to catch an OOM error while constructing a complex/fragmentary object built of too many small blocks like
JsonElement
hoping that GC would collect such a JSON tree once it fails to construct, so the process would survive. But yes, we’ll see.the argument against catching an
OutOfMemory
in any library code is strong. The only place I would be aware of where such a thing would potentially make sense is the very top level “catcher” in an application, for logging purposes only.