无法访问的代码编译器错误 [英] Unreachable code compiler error

查看:106
本文介绍了无法访问的代码编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码提供无法访问的语句编译器错误

The following code gives an unreachable statement compiler error

public static void main(String[] args) {
    return;
    System.out.println("unreachable");
}

有时为了测试目的,想要防止方法被调用,快速的方式来做它(而不是在它使用的任何地方注释)是立即从方法返回,以便该方法不做任何事情。我总是这样做,以避免编译器错误是这

Sometimes for testing purposes a want to prevent a method from being called, so a quick way to do it (instead of commenting it out everywhere it's used) is to return immediately from the method so that the method does nothing. What I then always do to get arround the compiler error is this

public static void main(String[] args) {
    if (true) {
        return;
    }
    System.out.println("unreachable");
}



我只是好奇,为什么是编译器错误?它会破坏Java字节码的某种方式,是保护程序员还是别的什么?

I'm just curious, why is it a compiler error?? Will it break the Java bytecode somehow, is it to protect the programmer or is it something else?

还有(这对我来说更有趣),如果编译java字节码做任何种类的优化(或即使它不)然后为什么不会检测到第二个例子中的公然不可达的代码?

Also (and this to me is more interesting), if compiling java to bytecode does any kind of optimization (or even if it doesn't) then why won't it detect the blatant unreachable code in the second example? What would the compiler pseudo code be for checking if a statement is unreachable?

推荐答案

无法访问的代码是无意义的,所以编译时错误是有帮助的。在第二个示例中不会检测到的原因是,像您预期的那样,用于测试/调试目的。它在规范中解释:

Unreachable code is meaningless, so the compile-time error is helpful. The reason why it won’t be detected at the second example is, like you expect, for testing / debugging purposes. It’s explained in The Specification:


if (false) { x=3; }

不会导致编译时错误。优化编译器可以
实现语句x = 3;将永远不会被执行,并且可以选择
从生成的类文件中省略该语句的代码,但
语句x = 3;

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

这种不同处理的基本原理是允许程序员使用
定义不可达标志变量,例如:

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

,然后编写如下代码:

if (DEBUG) { x=3; }

这个想法是可以将DEBUG
的值从false to true或从true到false,然后正确编译代码
,而不对程序文本进行其他更改。

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

http://docs.oracle.com/javase/specs /jls/se8/html/jls-14.html#jls-14.21

这篇关于无法访问的代码编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆