masmic
masmic

Reputation: 3564

Return statement with try/catch

I know that for many of you this can be a stupid question, but I'm learning android/java and I still have some concepts unclear.

In this case, I'm not sure on what is the best way to use the return statement within a try/catch block.

This is how I have declared my method where I need to use this:

public JSONArray parseXmlResponse(String response) {

        JSONArray addressComp = null;
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject = new JSONObject(response);
            addressComp = jsonObject.getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
        }catch (JSONException e) {
            e.printStackTrace();
        }
        return addressComp;
    }

As far as I know, here the method is always returning "addressComp", even if it is null.
But I've seen that other people would do it in this other way:

public JSONArray parseXmlResponse(String response) {

        JSONArray addressComp = null;
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject = new JSONObject(response);
            addressComp = jsonObject.getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
            return addressComp;
        }catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

But this makes me a bit confused.
By setting the return null here won't set the value to return always as null even if addressComp has a real value?

Upvotes: 1

Views: 2397

Answers (2)

Drifter64
Drifter64

Reputation: 1123

These methods achieve essentially the same thing. In the second way, it will only reach the return statement...

return addressComp;

... if everything above it in the try block is fine and doesnt throw an exception. Once this is hit, the method is complete and no more code is executed, so it would not reach the null return.

If, however, something goes wrong in the try block, it will go to catch, print the stack trace, and then program flow will fall through the try catch block, and return the null value. Note that as soon as the exception is thrown, NOTHING else in the try block will be run.

The second method is a little bit nicer because you can at least report issues. If you use the first way, you would want to check if the returned value is null before proceeding.

Upvotes: 1

codeMagic
codeMagic

Reputation: 44571

Setting the return null there won't set the value to return always as null even if addressComp has a real value?

No, once it hits the first return statement it will return addressComp and the return null line will never be executed. Just be sure you check for null on the variable that is taking that value if it will cause problems.

Edit

JSONArray jArray = parseXmlResponse(someString);
if (jArray != null)
{
     //run some code
}
else
{
    //it's null so run some other code
}

Upvotes: 3

Related Questions