xxx
xxx

Reputation: 197

Catching and throwing NullPointerException in Java

I am working with an App that accesses the internet for some data, before sending any requests I check for Internet connectivity, if available the app goes ahead and sends the request, if not, it holds back. The issues comes in if when the request is sent and connectivity is lost, the app keeps on waiting for data if it takes long, it proceeds and tries to access data that is not available, in this case it tries access value of the "JSON" object"json.toString()", I get a NullPointerException. I have put up a try catch block but I do not know if its working perfectly, I want it to toast a message that "there was a network problem" when if runs in such a situation, if anyone knows how I can do this please share, below is my code:

    @Override
    protected String doInBackground(String... params) {

        int success;
        try {
            // Building Parameters
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("username", username));
            param.add(new BasicNameValuePair("post_id", postID));
            param.add(new BasicNameValuePair("title", title));

            Log.d("request!", "starting");


            //Posting user data to script
            JSONObject json = jsonParser.makeHttpRequest(
                    ADD_TO_CART, "POST", param);

            // full json response
            Log.d("Post Comment attempt", json.toString());

            // json success element
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Comment Added!", json.toString());
                //finish();
                return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

Upvotes: 0

Views: 67

Answers (2)

Hilikus
Hilikus

Reputation: 10331

Why catch the NPE? just check before dereferencing json if it is not null

JSONObject json = jsonParser.makeHttpRequest(ADD_TO_CART, "POST", param);
if (json != null) {
  //do current code
} else {
  showToaster("There was an error in the connection");
}

In general, catching Unchecked Exceptions is kind of pointless IMO since you can't recover from them, but specially with NPEs since you can so easily verify if the exception will happen or not

Upvotes: 3

Rami Del Toro
Rami Del Toro

Reputation: 1150

The code below will catch a JSONException or a NullPointerExeption.

try{
     //Your Code

} catch (JSONException e) {
        e.printStackTrace();
} catch (NullPointerException npe){
      //Handle Exception
}

Upvotes: 1

Related Questions