第8章 异常

异常分类:

运行时异常:程序运行阶段,捕获,编译阶段可以不用处理

非运行时异常(编译时异常):编译阶段没有处理,编译器会给出错误提示

 

处理异常的方式:

1.try{    } catch(Exception){    } 处理

2. 将异常向后抛: throws exp1,exp2

 

手动引发异常:

throw

用法:throw new Exception();

throw异常对象; 

 

自定义异常:继承自Exception 

        

       【return的用法】:

publicclass Foo{

  public static void main(String args[]){

  try{return;}

   finally{System.out.println("Finally");}

   }

    }

 What is the result?

 A. print out nothing  B. print out "Finally"  C. compile error

Answer:B   Java的finally块会在return之前执行,无论是否抛出异常且一定执行.

5.publicclass Test{

   public static String output="";

   public static void foo(int i){

     try {

       if(i==1){

         throw new Exception();

       }

       output +="1";

     }

     catch(Exception e){

       output+="2";

       return;

     }

     finally{

       output+="3";

     }

     output+="4";

   }

   public static void main(String args[]){

     foo(0);

     foo(1);

     // 24)  

   }

}

Whatis the value of output at line 24?

Answer:13423如果你想出的答案是134234,那么说明对return的理解有了混淆,return是强制函数返回,本题就是针对foo(),那么当执行到return的话,output+="4";就不再执行了,这个函数就算结束了.

       【异常的匹配问题】:

importjava.io.*;

classExceptionTest{

           public static void main(Stringargs[]){

                 try{

                       methodA();

                 }

                 catch(IOException e){

                      System.out.println("caught IOException");

                 }

                 catch(Exception e){

                       System.out.println("caught Exception");

                 }

            }

      }

IfmethodA() throws a IOException, what is the result?  

Answer:caughtIOException

如果2个catch语句互换位置,那就会报错,catch只能是越来越大,也就是说:

catch的从上到下的顺序应该是: 孙子异常->孩子异常->父亲异常->老祖先异常.这么个顺序.