简体   繁体   中英

Unreachable return statement in Java

I was recently quickly writing this little function 5 minutes ago when i got the compiler error unreachable statement

private static boolean isTransientField(String name, Class beanClass) {
        try {
            Field field = beanClass.getDeclaredField(name);
            return (field.getModifiers() & Modifier.TRANSIENT) == Modifier.TRANSIENT;
        } catch (Exception e) {return false;}

        return false;//unreachable statement
    }

Apparently my last return false is unreachable but why if my catch block only runs in exceptional cases?

因为您在尝试中有一个return语句。

There are only two possible executions paths in your code.
1. The line

Field field = beanClass.getDeclaredField(name);

...works as expected and the next line returns:

return (field.getModifiers() & Modifier.TRANSIENT) == Modifier.TRANSIENT

2. An exception occurs and the return in the catch block executes.

Given those two paths, the third return statement cannot ever be reached.

因为在try块的末尾也有返回。

因为您的try块中也有返回值,所以无论如何,在try catch构造中都会达到返回值。

What you have is essentially the equivalent of the following:

if (something)
    return true;
else
    return false;
else
    return false;

Now, why would you have two else statements? That's right, you wouldn't.

While all the above are true, the reasoning is that your code will either process and return successfully via the happy path, or it will throw an exception and be handled accordingly, so in essence, you've provided an if/else path of execution. The compiler will never reach the third return statement. If you removed the return false; from the catch block, the warning would go away. You would get the same warning if you were to handle your checked exception in some way (re-throw up the stack) because the code will either return as expected or throw and exception (another if/else path of execution).

Just to reiterate, don't use try/catch blocks for logical flow. The catch block should be used for handling exceptions/errors gracefully. Secondly, any function that is NOT declared void must return some form of the declared type, in your case a boolean value.

Possible solution

private static boolean isTransientField(String name, Class beanClass) 
{
    try 
    {
        Field field = beanClass.getDeclaredField(name);
        if((field.getModifiers() & Modifier.TRANSIENT) == Modifier.TRANSIENT)
        {
            return true;
        }
        else
        {
            return false;
        }

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

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