HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaMinor

Check if a value exists or catch an exception

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
exceptioncatchvalueexistscheck

Problem

I am parsing a response from server, and in case it contains the fields "chunk_number"(J_ID_CHUNK_NUMBER) and "total_chunk_number"(J_ID_CHUNK_TOTAL), I want to check whether I should request another chunk or not. Not a complicated task. Yet I doubt what would be a better way to implement?

Option 1 - using try catch:

private int getNextChunkNumber(JSONObject jUpdate) {
    try {
        int current;
        int total;
        current = jUpdate.getInt(J_ID_CHUNK_NUMBER);
        total = jUpdate.getInt(J_ID_CHUNK_TOTAL);
        if (current < total) {
            return current + 1;
        }
    }
    catch(JSONException e) {
        // This is an empty exception because it merges with the default result (-1)
    }
    return -1;
}


Option 2 - using the has method:

private int getNextChunkNumber(JSONObject jUpdate) {
    int current;
    if (jUpdate.has(J_ID_CHUNK_NUMBER) &&
        jUpdate.has(J_ID_CHUNK_TOTAL)) {
        current = jUpdate.getInt(J_ID_CHUNK_NUMBER);
        if (current < jUpdate.getInt(J_ID_CHUNK_TOTAL)) {
            return current + 1;
        } 
    }
    return -1;
}

Solution

I would recommend that you use option 2, especially since you have the ability to avoid the exception (by using the has method).

Exceptions should be used in exceptional circumstances (e.g. You might expect getInt to throw an exception if J_ID_CHUNK_TOTAL exists but does not contain a character which can be parsed to an integer). In which case you would want to wrap the call to that in a catch.

I would also suggest that you do a null check against the jUpdate object before using it.

Context

StackExchange Code Review Q#9876, answer score: 8

Revisions (0)

No revisions yet.