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+ 已查看

开启你的 职业生涯

完成课程以获得认证

开始学习
广告
© . All rights reserved.