无法到达的return语句仍会引发错误 [英] Unreachable return statement still throws error
问题描述
我有一个非常简单的代码段:
I have this very simple code snippet:
static String getInput() throws IOException{
if(in.ready()){
return in.readLine().trim();
}
System.err.println("Please provide more input in order to execute the program.");
System.exit(0);
return "";
}
据我所知,JVM无法在代码末尾执行return语句.但是,如果我将这一行注释掉,java将抱怨缺少return语句. JVM为什么不能识别System.exit(0)不允许执行任何其他代码,但是如果返回将不允许执行代码,则会抱怨无法到达的语句? 我认为最后的return语句是多余的,可能会使其他开发人员感到困惑,所以java为什么不让我摆脱它呢?
By what I think I know, there is no possible way that the JVM will execute the return statement at the end of the code. But if I comment this line out, java will complain about a missing return statement. Why doesn't the JVM recognize that a System.exit(0) will not allow any other code to execute, but complains about unreachable statements if a return will not allow code to be executed? I think the return statement at the end is redundant and might be confusing to other devs, so why won't java let me get rid of it?
推荐答案
为什么JVM不能识别System.exit(0)不允许执行任何其他代码,但是如果返回将不允许执行代码,则会抱怨语句不可达?
Why doesn't the JVM recognize that a System.exit(0) will not allow any other code to execute, but complains about unreachable statements if a return will not allow code to be executed?
不是JVM,而是编译器.而且编译器不知道 library 调用会做什么-它只知道 language 规则. (特别是 JLS第14.21节,无法访问的语句 )
It's not the JVM - it's the compiler. And the compiler doesn't know what library calls will do - it only knows the language rules. (In particular, JLS section 14.21, Unreachable Statements.)
例如:
public int foo() {
alwaysThrow();
// This is required.
return 10;
}
private static void alwaysThrow() {
throw new RuntimeException();
}
vs
public int foo() {
throw new RuntimeException();
// Error: unreachable statement
return 10;
}
这种简单的内联改变了代码的意义,甚至影响了编译器.
That simple inlining changes the meaning of the code as far as the compiler's concerned.
这可以通过返回类型为从不"来修复",以表示此方法从不正常返回-它挂起或抛出异常",但这根本不是该语言的一部分(并且将具有自己的语言)并发症).如果您有兴趣,埃里克·利珀特(Eric Lippert)关于C#(位置相似)有一些关于该主题的博客文章:部分两个.
This could be "fixed" by having a return type of "never" - to indicate "this method never returns normally - it either hangs or throws an exception" but that's simply not part of the language (and would have its own complications). If you're interested, Eric Lippert has a couple of blog posts on this topic with regard to C# (which is in a similar position): part one, part two.
这篇关于无法到达的return语句仍会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!