從頭認識java-10.2 異常參數以及捕獲異常

來源:互聯網
上載者:User

從頭認識java-10.2 異常參數以及捕獲異常

這一章節我們來簡單討論一下異常參數以及捕獲異常。

1.異常參數

在異常當中我們可以加入參數,從而使異常更加清晰。

package com.ray.ch10;public class Test {public static void main(String[] args) {throw new RuntimeException(運行時異常);}}


輸出:

Exception in thread main java.lang.RuntimeException: 運行異常
at com.ray.ch10.Test.main(Test.java:7)

從輸出結果可以看見,我們可以通過參數傳遞一些資訊給程式員,使得代碼異常更加明確。

 

2.捕獲異常

(1)try塊

package com.ray.ch10;public class Test {public static void main(String[] args) {try {//dosomething} finally {}}}


注意:try塊需要聯合finally一起使用,其實這樣就保證即便有異常,也會有最終的處理。

try只是嘗試各種語句,然後有異常就會在異常點停止執行代碼,最後有finally收尾,但是在這個過程裡面不處理異常。(當然我們也可以把finally看作是一種處理)

package com.ray.ch10;public class Test {public static void main(String[] args) {try {throw new RuntimeException();} finally {System.out.println(dosomething);}}}

 

(2)try catch

package com.ray.ch10;public class Test {public static void main(String[] args) {try {throw new RuntimeException(拋出運行時異常);} catch (RuntimeException e) {System.out.println(處理運行時異常);e.printStackTrace();} catch (Exception e) {System.out.println(處理異常);e.printStackTrace();}}}



輸出:

處理運行時異常
java.lang.RuntimeException: 拋出運行時異常
at com.ray.ch10.Test.main(Test.java:7)

 

從輸出結果可以看到,處理異常的步驟:

(1)發現異常

(2)找到自己類型的異常,一般來說,異常的類型就已經是一個異常資訊。

(3)處理異常

(4)拋出異常,並在異常地點斷開代碼的執行

 

注意:一般是先找到自己類型的異常,如果找不到,再向上轉型。

 

3.異常處理的模型

異常處理模型分為兩種:斷開與恢複

我們上面示範的都是斷開的處理模型,如果是恢複模型,則把try放到while裡面,直到處理結果滿意為止,但是這樣增添了無數維護成本,因此最終大部分的情況都只是使用斷開模型。

 

總結:這一章節簡單講述了異常參數以及捕獲異常。

 

 

 

聯繫我們

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