我正在 eclipse 中使用 Java 時收到一項警告,上面寫著“dead code”。這是什麼意思?


在 Java 中永遠不會到達並且在程式生命週期內永遠不會被執行的程式碼塊/語句被稱為不可到達塊/語句。

public class UnreachableCodeExample {
   public String greet() {
      System.out.println("This is a greet method ");
      return "Hello";
      System.out.println("This is an unreachable code ");
   }
   public static void main(String args[]) {
      new UnreachableCodeExample().greet();
   }
}

死程式碼

死程式碼是一種不可到達的程式碼,但它不會產生編譯時錯誤。但是,如果你在 eclipse 中執行它,它會給你一個警告。

示例

在以下 Java 程式中

 即時演示

public class UnreachableCodeExample {
   public void greet() {
      System.out.println("This is the greet method ");
      if(true){
         return;
      }
      System.out.println("This is a dead code ");
   }
   public static void main(String args[]) {
      new UnreachableCodeExample().greet();
   }
}

輸出

This is the greet method

如果你在 eclipse 中執行相同的程式,它會像下面一樣發出警告:

更新於:2020 年 6 月 29 日

903 次瀏覽

開啟你的 事業

完成課程認證

開始
廣告
© . All rights reserved.