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?
Because you have a return statement within the try.
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.
Because you've also got a return at the end of the try block.
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.
Because you also have a return in your try block, so no matter what, a return is reached within the try catch construct.
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();
}
}
精彩评论