Java.異常:自訂異常類,throw,throws,try...catch,finally__Java

來源:互聯網
上載者:User

//自訂負數異常類 class myException extends Exception { public myException(String msg) //構造方法 { super(msg); //調用Exception異常類的構造方法 } } class Test { public int devide(int x,int y) throws myException //由於方法體內使用了throw,又沒有try....catch進行處理,所以用throws聲明 { if (y<0) throw new myException("異常資訊:被除數小於零。"); //方法內使用了throw拋出了異常對象,如果方法內沒有try....catch語句對這個拋出的異常進行處理,則此方法應聲明拋出異常throws XxxException,由該方法的調用者負責處理。 if (y==0) throw new myException("異常資訊:被除數不能為零。"); return x/y; } } class TestException { public static void main(String [] args) { try { int result=new Test().devide(3,1); //int result=new Test().devide(3,0); //int result=new Test().devide(3,1); System.out.println("the result is "+result); //return; } catch(myException e) { System.out.println(e.getMessage()); //System.exit(0); } /* //ArtthmeticException 算術運算異常類。比如除以零。 catch(ArithmeticException e) { System.out.println("異常資訊:"+e.getMessage()); //調用了異常類的getMessage方法 System.out.print("異常堆棧跡:"); e.printStackTrace(); //調用異常類printStackTrace方法,列印異常詳情 } */ catch(Exception e) //前面沒能處理的所有異常都由Exception處理。由於Exception是所有異常類的父類,所以這句不能放到其他語句的前面。否則編譯的時候會出錯。 { System.out.println("異常資訊:"+e.getMessage()); //return; } finally { System.out.println("the pragram is running into finally"); } //finally語句塊。即使try和catch語句塊使用return語句退出了當前方法或break跳出某個迴圈,相關的finally代碼塊都不會受影響的執行。 //finally代碼塊唯一不能執行的情況是在被保護的代碼塊中執行了System.exit(0) //每個try語句必須有一個或者多個catch語句與之對應,try代碼塊、catch代碼塊及finally代碼塊之間不能有其他語句。 System.out.println("the pragram is running here!"); //當catch語句中使用了return或者System.exit(0)語句是,這裡的代碼就不會執行了。 } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.