Java会出现"unreachable code"错误的几个例子

 1 public class exam {
 2     static int num=5;
 3     static int m1(){
 4         try{
 5             num=6;
 6             throw new NullPointerException();
 7             System.out.println("111");    //编译不通过
 8         }catch(ArrayIndexOutOfBoundsException e){
 9             num=10;
10             System.out.println("222");
11         }catch(Exception e){
12             num+=1;
13             System.out.println("333");
14             return num;
15         }finally{
16             num=10;
17             System.out.println("444");
18             throw new NullPointerException();
19         }
20     }
21     
22     public static void main(String[] args) {
23         try{
24             m1();
25             num=20;
26         }catch(Exception e){
27             num+=1;
28             System.out.println("555");
29         }
30         System.out.println(exam.num);
31         
32     }
33 }

输出结果:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable code

at exam.m1(exam.java:8)
at exam.main(exam.java:25)

1. throw关键字

Java代码:  
  1. public void XXX() throws Throwable{  
  2.     throw new Throwable();  
  3.     System.out.println("test");  
  4. }  

2. return关键字

Java代码 : 
  1. public void XXX() {  
  2.     return;  
  3.     System.out.println("test");  
  4. }  

3. continue关键字

Java代码:  
  1. public void XXX() {  
  2.     for(int i=0; i<10; i++) {  
  3.         continue;  
  4.         System.out.println("test");  
  5.     }  
  6. }  

4. break关键字

Java代码:  
  1. public void XXX() {  
  2.     for(int i=0; i<10; i++) {  
  3.         if(i==5) {  
  4.             break;  
  5.             System.out.println("test");  
  6.         }  
  7.     }  
  8. }  

5. while(true):

Java代码:  
  1. public static void XXX() {  
  2.     while(true);  
  3.     System.out.println("when?");  
  4. }  


原文地址:https://www.cnblogs.com/jiangyi666/p/5761339.html