简体   繁体   中英

Why is the last line of this Java code unreachable

I've been writing a parse for a language and I am getting an unexpected problem in Java. Specifically, the Java compiler says that the return statement at the end of this code is unreachable.

        StringBuffer buf = new StringBuffer();
        Token tok2;
        do {
            tok2 = tokenizer.nextToken();
            if (tok2 == null) throw new ParseException("Unexected end of file", tok2.endLine, tok2.endColumn);

            switch (tok2.type) {
            case Token.IDENTIFIER:
            case Token.PACKAGE:
                buf.append(tok2.token);
            default:
                throw new ParseException("Illegal character: expected identifier or .", tok.beginColumn, tok.beginLine);
            }

        } while (tok2.type != Token.SEMI_COLON);
        return new PackageElement(buf.toString(), tok.beginLine, tok.beginColumn, tok2.endLine, tok2.endColumn);

tok2.type is an int, and the constants are ints, and the ParseException is a checked exception...

I understand what "unreachable" means and I have written many parses both from scratch and via tools like JavaCC, but I have been looking at this code for hours, and it seems correct to me...

Any help understanding why the return statement is unreachable would be much appreciated!

Your case s are missing break s, which means each case falls through. That means that one of two things will happen:

  • if tok2 == null , an exception is thrown
  • otherwise, the switch block is triggered. Whether or not either case is hit, flow falls through to the default case, and an exception is thrown

In either case, the first run through the do block is guaranteed to throw an exception, and thus anything following it is unreachable.

Solution: add break statements, like this:

case Token.PACKAGE:
    buf.append(tok2.token);
    break; // <--- here
default:
    // etc

Once you reach the semi colon token, the default case is hit and an exception thrown. This is the only exit from the loop.

You do not have a break statement anywhere, which means that the default statement is going to get executed - resulting in an Exception being thrown for certain no matter what. HEnce the return statement will never be hit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM