0

if 引数が true の場合に、if else ケースで Java プログラムがエラーにならないのはなぜですか。なぜ例外を作らないのですか?たとえば、ここで method1 と method2 は到達不能ステートメントがあっても (コンパイル) エラーを発生させませんが、method3 はコンパイル エラーを発生させます。最初にコードを注意深く読んで、答えを出してください。

    public int method1() {
        if(true) {
            return 1;
        } else {
            return 2;//unreachable statement but doesn't make exception
        }
    }

    public int method2() {
        if(true) {
            return 1;
        } else if (true) {
           return 2;//unreachable statement but doesn't make exception
        } else {
            return 3;//unreachable statement but doesn't make exception
        }
    }

    public int method3() {

        if(true) {
            return 1;
        } else if (true) {
           return 2;//unreachable statement but doesn't make exception
        } else {
            return 3;//unreachable statement but doesn't make exception
        }

        return 3;//unreachable statement but makes exception
    }

Javaは厳密なコンパイルをサポートしていませんか? この問題の背後にある原則は何ですか?

4

2 に答える 2

6

この言語では、if-then-else の特殊なケースを作成することにより、条件付きコンパイルが可能です。これにより、コンパイル時にコード ブロックを簡単にオンまたはオフにすることができます。

到達不能ステートメントに関するJava言語仕様のセクションから:

   As an example, the following statement results in a compile-time error:

          while (false) { x=3; }

   because the statement x=3; is not reachable; but the superficially similar case:

          if (false) { x=3; }

   does not result in a compile-time error. 

と:

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

          static final boolean DEBUG = false;

   and then write code such as:

          if (DEBUG) { x=3; }

   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.
于 2012-10-14T14:27:06.643 に答える
0

コンパイラの作成者は、最初のケースはエラーを生成する価値がなく、最後のケースはそうであると判断したと言えます。彼らが何を考えていたのかは推測することしかできませんが、最初の 2 つのケースでは到達可能性を判断できましたが、誰かが誤ってこのようなコードを書く可能性は非常に低いと思います。デバッグメカニズムとして明示的に導入される可能性が高くなります。さらに、そのようなエラー (エッジ ケース) を検出するための評価を追加するコストは、おそらく価値がありません。いずれにせよ、そのエラーは迷惑であり、役に立ちません。最後のケースでは、プログラマーはこのようなコードを簡単に書き、最後のステートメントに到達できないことに気付かず、エラーが発生する可能性があります。

于 2012-10-14T14:24:08.347 に答える