Replies: 1 comment
-
The reason is because interfaces this method has to use declare throwing So despite method being theoretically usable on any given type, there are error conditions that may mean that in actuality some types (or possibly instances) will fail to be serialized. Such condition is reported as one of I would not recommend swallowing exception, except if method can signal error condition in some other way (like returning |
Beta Was this translation helpful? Give feedback.
-
Describe your Issue
Hi
What is the reason for
ObjectMapper.writeValueAsString(Object value)
to declare that it throws aJsonProcessingException
. The method description says that this method can serialise any java object to String. So it should not and cannot throw any exceptions, or why does it?The reason I am asking is because when I use this method, I must provide try-catch clause for the
JsonProcessingException
and I really do not understand, why I am doing it or how this could happen, so I end up adding a comment /must never happen/ and rethrow it as a runtime exception. If there is a legitimate reason or possibility for the method to throwJsonProcessingException
could you please provide one? Then I could at least have some meaningful logic to deal with it.I looked at the source code of
ObjectMapper.writeValueAsString()
and I don't see how or why it would throw aJsonProcessingException
. The methods it calls throwIOException
which makes it hard to pinpoint where and ifJsonProcessingException
exception is thrown if it's thrown at all, but it's a separate problem.I looked at libraries that use this method and some of them call it in try - catch with empty catch clause, basically ignoring it. Others re-throw it as some kind of runtime exception.
Please advise.
Thanks.
Beta Was this translation helpful? Give feedback.
All reactions