I have a piece of code that encodes some kind of business data in a JSON string:
public String encodeDataAsJsonString(Data data) throws JSONException {
JSONObject o = new JSONObject();
o.put("SomeField1", data.getSomeProperty1());
o.put("SomeField2", data.getSomeProperty2());
...
return o;
}
The thing is:
- JSONException is a checked exception, but
- I don't really know how to handle it at compile time. If a JSONException really occurs, it's probably a bug in the the code and should be handled by the regular "global uncaught exception handler" which is already there (e.g. this), and which already performs all the necessary logging and cleaning up.
Thus, I ended up doing this in the calling method:
...
try {
encoded = encodeDataAsJsonString(data);
} catch (JSONException e) {
throw new RuntimeException(e);
}
...
It seemed like a lesser evil than adding a throws JSONException
to every method up the call stack. However, it still feels dirty, hence my question:
If I want some specific checked exception to go the "regular unchecked exception route", is rethrowing it as a RuntimeException the correct idiom to use?