浪潮優派培訓java筆記:第8章 異常

第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的從上到下的順序應該是: 孫子異常->孩子異常->父親異常->老祖先異常.這麼個順序.

發佈了40 篇原創文章 · 獲贊 39 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章