java異常處理Exception,異常處理exception

來源:互聯網
上載者:User

java異常處理Exception,異常處理exception

       我看別人的面經中有一道題目就問到了Exception,即java的異常處理的,我以前也學了java的異常處理,但是我查了下,看了別人的部落格關於寫的exception異常處理,我發現,自己學的不牢固,只學到了一點皮毛而已,在看了那麼多部落格和資料後,我做下總結吧,不然我大腦都混亂了。

      java的中異常祖先是Throwable,Throwable的直接子類是Exception和Error。

      Error通過單詞我們就知道,是錯誤的意思,這種錯誤一般是jvm運行產生的錯誤,出現這種錯誤,我們的程式不能解決,比如記憶體溢出oom,堆溢出等。這種錯誤,我們不必處理,直接讓jvm拋出報錯,我們沒辦法解決就不管了。

     Exception中文意思是異常,那麼Exception又分為檢查性異常和非檢查性異常。比如RuntimeException類及子類就是非檢查性異處,表示運行時出現的異常,有數組越界,null 指標異常,我們也可以不進行處理,讓jvm自己拋出異常,當然如果我們可以預見這種異常的話,最好在程式中進行判斷檢查,程式寫健壯些,有的這種異常就可以避免了。effect java有這種處理的推薦,具體的可以看看這本書。

    Exception還有一類是檢查性異常,這是除RuntimeException類及子類外的Exception類和Exception類的其他子類。檢查性異常,必須要進行異常處理的或者拋出,否則編譯器會報錯。

      

   異常處理一般用到以下幾個關鍵字try,catch,finally,throws,throw,下面我逐個做一個說明。

    try:

    對於可能會拋出異常的代碼一般放在try{}代碼塊中,比如:

 

try {
  int   i=2/0;t.test1();//System.out.println("kkk"+st);} catch (Exception e) {// TODO Auto-generated catch blockSystem.out.println("i will catch you....");e.printStackTrace();}


上面的代碼2/0,肯定會拋出異常的,所以需要放在try{}塊中,在try塊中,如果哪一行拋出了異常,那麼try塊後面的代碼將不再執行,將直接進入異常處理代碼塊。


  catch:

    catch(Excetion e){}這種結構是用來處理,try代碼塊中拋出的異常的,可以有很多的catch代碼塊,不過要注意的是,當有很多catch代碼塊,並且catch裡面的參數有父子關係的時候,catch裡面的參數一定要是子類在前面,父類在後面,因為按catch代碼塊出現的先後順序匹配拋出的異常,一旦拋出的異常是哪個catch裡面參數的子類或同類,那麼就可以被這個catch代碼塊進行處理,那麼其他的catch代碼塊就算也符合這種條件也不在進行處理了,如果有finally代碼塊的話就直接進入finally代碼塊中,沒得則直接運行catch代碼塊後面的代碼了。


    finally:

    finally代碼塊是異常處理中一定會執行的代碼塊,就算沒得異常也會執行,有異常則進入catch代碼塊中處理後,在進入finally中處理。

    在這裡要注意一點,假如在try代碼塊中有return 語句,那麼也是先執行finally裡面的代碼塊後在執行return語句的。

 還需注意一點的是,函數的返回值,是最後活動棧的棧頂的值。如果try進行return了,那麼在finally中我也進行return,那麼finally代碼塊裡面的return的值在棧頂,所以會返回finally中return的值。有如下測試代碼。

package com.wj.exception;public class TestException3 {public String testException(){try{return "I am in try";}finally{return "I am in finally";}}public static void main(String[] args) {// TODO Auto-generated method stubTestException3 te=new TestException3();System.out.println(te.testException());}}


運行結果是:

   I am in finally


注意我這裡是測試所以在finally中進行return了,一般不推薦在finally中進行return。



    throws:

    throws的用法是在      函數名(參數1,參數2.....)throws 異常類1,異常類2,異常類3.....{}

   throws是表明這個函數可能會有異常產生,但是函數不進行異常處理,函數將向上拋異常,把異常處理交給函數的調用處進行處理,如果調用處,不進行處理則可以在進行向上拋。。。直到有地方進行try{}catch(){}異常處理,或者最後拋給jvm(不建議這麼使用)。

package com.wj.exception;public class TestException3 {public String testException() throws Exception{/*try{return "I am in try";}finally{return "I am in finally";}*/System.out.println("我不進行異常處理,我將異常向上拋,throws");int i=2/0;System.out.println("有異常我將得不到執行。。。。");return "我是使用throws拋的異常";}public static void main(String[] args) {// TODO Auto-generated method stubTestException3 te=new TestException3();try {System.out.println(te.testException());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


輸出結果:

<span style="font-size:18px;">我不進行異常處理,我將異常向上拋,throwsjava.lang.ArithmeticException: / by zeroat com.wj.exception.TestException3.testException(TestException3.java:13)at com.wj.exception.TestException3.main(TestException3.java:24)</span>



       throw:

     throw的作用是具體的拋出一個異常類對象,一般在方法裡面使用。當在try代碼塊中使用的時候,直接進入catch代碼塊中進行處理。比如:

package com.wj.exception;public class TestException3 {public String testException(){try{throw new Exception("i is throw exception");}catch(Exception e){System.out.println("我處理throw拋出的異常");}finally{System.out.println("我執行finally代碼塊\n");}System.out.println("異常處理結束!!!");return "I am in finally";}public static void main(String[] args) {// TODO Auto-generated method stubTestException3 te=new TestException3();    System.out.println(te.testException());}}


允許結果:

我處理throw拋出的異常
我執行finally代碼塊


異常處理結束!!!
I am in finally



        throw手動拋出的異常需要從裡到到外尋找處理的try代碼塊,沒有處理話,就需要把方法後面加throws,把異常向上拋。看如下代碼:


    1

package com.wj.exception;public class TestException3 {public String testException(){try{int i=3/0;}catch(Exception e){throw new Exception();}finally{System.out.println("我執行finally代碼塊\n");}//System.out.println("異常處理結束!!!");return "I am in finally";}public static void main(String[] args) {// TODO Auto-generated method stubTestException3 te=new TestException3();    System.out.println(te.testException());}}





2

上面的代碼在編譯器裡面會出現錯誤,提示我們使用throws拋出異常,或者把throw new Exception()進行因此處理,改成這樣的

<pre name="code" class="java">package com.wj.exception;public class TestException3 {public String testException() {try{int i=3/0;}catch(Exception e){try {throw new Exception();} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}finally{System.out.println("我執行finally代碼塊\n");}//System.out.println("異常處理結束!!!");return "I am in finally";}public static void main(String[] args)  {// TODO Auto-generated method stubTestException3 te=new TestException3();    System.out.println(te.testException());}}



輸出結果:

java.lang.Exceptionat com.wj.exception.TestException3.testException(TestException3.java:11)at com.wj.exception.TestException3.main(TestException3.java:32)我執行finally代碼塊I am in finally









3

或者說是這樣的:

<pre name="code" class="java">package com.wj.exception;public class TestException3 {public String testException()  throws Exception{try{int i=3/0;}catch(Exception e){throw new Exception();}finally{System.out.println("我執行finally代碼塊\n");}//System.out.println("異常處理結束!!!");return "I am in finally";}public static void main(String[] args)  {// TODO Auto-generated method stubTestException3 te=new TestException3();    try {System.out.println(te.testException());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

輸出結果:


我執行finally代碼塊java.lang.Exception<span style="white-space:pre"></span>at com.wj.exception.TestException3.testException(TestException3.java:11)<span style="white-space:pre"></span>at com.wj.exception.TestException3.main(TestException3.java:28)







4

這樣改,很簡單,但是還有一種更加奇葩的改法,可以使編譯器不出錯,如下:

package com.wj.exception;public class TestException3 {public String testException()  {try{int i=3/0;}catch(Exception e){throw new Exception();}finally{System.out.println("我執行finally代碼塊\n");return "I am in finally";}//System.out.println("異常處理結束!!!");//return "I am in finally";}public static void main(String[] args) {// TODO Auto-generated method stubTestException3 te=new TestException3();    System.out.println(te.testException());}}

輸出:

我執行finally代碼塊
I am in finally




     發現沒有第四個代碼,本來是跑出了一個異常的,但是沒有輸出任何的異常資訊。而且把函數返回值改為void,在finally裡面不使用return,則又會報錯,這一點我不是很明白了,難道在catch裡面使用throw拋出的異常,在finally代碼塊裡面使用return語句後,就被處理了嘛?要是被處理了怎麼沒得異常輸出,還是輸出的異常資訊在棧裡面被覆蓋了?知道怎麼回事的朋友,可以交流下。


看了上面那麼多,你是否對java中的異常有一定理解了?

我在部落格http://blog.csdn.net/hguisu/article/details/6155636裡面看到一個例子,貌似比較經典,就借用下了,代碼如下了:

package com.wj.exception;public class TestException1 {boolean testEx() throws Exception {  boolean ret = true;  try {  ret = testEx1();  } catch (Exception e) {  System.out.println("testEx, catch exception");  ret = false;  throw e;  } finally {  System.out.println("testEx, finally; return value=" + ret);  return ret;  }  }  boolean testEx1() throws Exception {  boolean ret = true;  try {  ret = testEx2();  if (!ret) {  return false;  }  System.out.println("testEx1, at the end of try");  return ret;  } catch (Exception e) {  System.out.println("testEx1, catch exception");  ret = false;  throw e;  } finally {  System.out.println("testEx1, finally; return value=" + ret);  return ret;  }  }  boolean testEx2() throws Exception {  boolean ret = true;  try {  int b = 12;  int c;  for (int i = 2; i >= -2; i--) {  c = b / i;  System.out.println("i=" + i);  }  return true;  } catch (Exception e) {  System.out.println("testEx2, catch exception");  ret = false;  throw e;} finally {  System.out.println("testEx2, finally; return value=" + ret);  return ret;  }  }  /** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubTestException1 testException1 = new TestException1();  try {  testException1.testEx();  } catch (Exception e) {  System.out.println("結束\n");e.printStackTrace();  }  }}

如果不看答案,你能說出運行結果嘛?你可以到自己的編譯器中運行下看下結果,在進行debug下,看看是否和你想的一樣了。







      上面啟動並執行結果如下:

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false


   我進行過debug,所以我清楚啟動並執行流程,但是對於內部的機制,還有點疑點,就像我在4所說的,finally中的return 會覆蓋throw拋出的異常一樣,真的是這樣的嘛,如果是這樣的話,上面的代碼就能分析出和運行一樣的輸出結果了,可以試試,一起交流下。



本文原創,轉載請著明:http://blog.csdn.net/j903829182/article/details/39808307























































































































java中異常處理時IOException可以用Exception代替

可以,IOException是Exception 的一種,也就是說如果你換成了Exception的話除了能捕捉到IOException還能捕捉到其他的。。如果同時用的話,必須是先用範圍小的也就是IOException捕捉 然後再用範圍大的Exception捕捉;反過來是不成立,因為Exception所有的異常都捕捉完了,那還要IOException捕捉什麼呢?
 
java出現 NullPointException異常解決方案

你好,發生null 指標,好好檢查下,是否有變數為空白,而你沒有去判斷,就直接使用,就會出現
例如:
String s = null; //對象s為空白(null)
int length = s.length();//發生null 指標異常
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.