开发者

Why is this java code executing multiple return statements

I have a function that during execution while in the deb开发者_如何学编程uger runs both the return statment inside the if and then the return statment at the end of the function.

I'm confused I thought the return statment returned the value and stopped the flow of execution in the method?

I've got it to work, but would like to understand why it is doing this.

As an example in the below. The json will fail on the answer adn the createapprove block. It gets to create fail and ret becomes true (As the json parsed). The return retval runs and then the code jumps down to the final return retval and executes that as the return for the function.

I'm walking through the code in ecipse in debug mode with the program running on the android emulator.

public static ComModelFromServer createModelFromJSON(String json) throws JSONInvalidException {     
     boolean ret = false;
     ComModelFromServer retval = null;

     //Answer Block
     Answer a = new AnswerAsset();
     ret = a.tryToParseFromJSON(json);
     if(ret == true) {
        retval = a;
        return retval;
    }

    Create cr = new CreateApprove();
    ret = cr.tryToParseFromJSON(json);
    if(ret == true) {
        retval = cr;
        return retval;
    }

    cr = new CreateFail();
    ret = cr.tryToParseFromJSON(json);
    if(ret == true) {
        retval = cr;
        return retval;
    }

    if(ret == false) { 
        throw new JSONInvalidException("couldn't create model from JSON");
    }

    return retval;
}


There's probably no problem with this. The compiler probably compiled the return retval inside the if statements into a jump that jumps to the return at the end of the function, which already has a return retval statement. The debugger showing the odd flow control doesn't mean that there is anything wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜