Java 中的無法到達的程式碼錯誤


無法到達的程式碼錯誤在程式碼無法因各種原因(包括死迴圈、無法到達程式碼行前的 return 語句)而編譯時發生。

讓我們看一個示例 −

示例

 即時演示

public class Demo{
   public static void main(String args[]){
      int val = 5;
      for (;;){
         if (val == 5){
            break;
            System.out.println("If the condition is not true, this line would be printed. ");
         }
      }
   }
}

輸出

/Demo.java:11: error: unreachable statement
System.out.println("If the condition is not true, this line would be printed. ");
^
1 error

名為 Demo 的類包含 main 函式,並且值為已定義,並且此值為檢查值並且執行空 'for' 迴圈。如果找到該值,則控制跳出迴圈,否則會列印訊息。由於它是一個死迴圈,因此會出現一條無法到達的語句錯誤。

更新日期:09-Jul-2020

1K+ 已檢視

開啟你的 職業生涯

完成課程以獲得認證

開始學習
廣告