I am using JSONObject to build a JSON response. The problem I’m facing is how to handle the exception that .put() throws. I surrounded my code with a try catch, but I want to output JSON in my catch as well. I’ve been doing this by hand as seen below, but this seems prone to errors.What is the right way to handle this exception?
try{
myResponse.put("successful",true);
resp.getOutputStream().print(myeResponse.toString());
} catch (JSONException e) {
resp.getOutputStream().print("{\"successful\":false, \"error\":\"Changes could not be saved. Please reload the page and try again.\"}");
}
What you need to figure out is when the
put()method ofJSONObjectwould throwJSONException.From the Javadoc
So, all you need to take care is that your key is not null which would surely be the case because your key is
"successful".