views:

21

answers:

2

I have a pretty basic Servlet

public class DreambearLoginServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        JSONObject ret = new JSONObject();

        try {

            // handle the request
            try {

                String action = req.getParameter("action");

                if (action.equals("login")) {

                    ...

                } else if (action.equals("checklogin")) {

                    ...

                } else {
                    throw new RuntimeException("Action invalid");
                }

            } catch (Exception e) {
                ret.put("error", e.getMessage());
                e.printStackTrace();
            }

            // write response
            resp.setContentType("application/json");
        resp.getWriter().print(ret.toString());
            resp.getWriter().flush();

        } catch (JSONException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }



}

Now, if I call this without specifying the query string parameter action, a NullPointerException should be thrown upon the statement action.equals("login"). This would result in the catch code being executed and the JSON output being {"error": "Whatever NPE says"}. Strangely enough, the JSON output is just {}. How could this be?

A: 

You are correct, if a NPE happens it will be caught by your catch clause. So you are right, it cannot be!

  • are you sure it's a get request?
  • are you sure your code is not stopping somewhere else?
  • is action maybe set to empty?
  • is maybe the message in NullPointerException empty?
krico
+3  A: 

e.getMessage() is null for NullPointerException and JSONObject.put() documentation says:

Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if it is present.

So, as expected, nothing is added to your JSON object.

unbeli
That's indeed the problem. What a strange API design decision by the JSON group; JSON supports keys with "null" values, doesn't it? Anyway, thanks.
Bart van Heukelom