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

 public class exam {
static int num=5;
static int m1(){
try{
num=6;
throw new NullPointerException();
System.out.println("111");    //编译不通过
}catch(ArrayIndexOutOfBoundsException e){
num=10;
System.out.println("222");
}catch(Exception e){
num+=1;
System.out.println("333");
return num;
}finally{
num=10;
System.out.println("444");
throw new NullPointerException();
}
} public static void main(String[] args) {
try{
m1();
num=20;
}catch(Exception e){
num+=1;
System.out.println("555");
}
System.out.println(exam.num); }
} 输出结果:

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. }


上一篇:win7下wamp扩展memcache


下一篇:从OC到Swift(7) - 资源名管理