從頭認識java-10.3 自訂異常類型

來源:互聯網
上載者:User

從頭認識java-10.3 自訂異常類型

這一章節我們來簡單討論一下自訂異常類型。

一般來說java裡面定義的異常類型已經夠我們使用,但是,在實際操作中我們還需要其他一些自訂的類型。

在異常部分,我們一般使用類的名字就基本足夠的。

下面是最簡單的自訂異常類型:

 

package com.ray.ch10;public class Test {public static void main(String[] args) throws SimpleException {throw new SimpleException();}}class SimpleException extends Exception {}

然後在開發中,上面的代碼太簡單,沒什麼用,我們再擴充一下:

 

 

package com.ray.ch10;public class Test {public static void main(String[] args) throws SimpleException {// throw new SimpleException();throw new SimpleException(自訂異常);}}class SimpleException extends Exception {public SimpleException() {}public SimpleException(String msg) {super(msg);}}

輸出:

 

com.ray.ch10.SimpleException: 自訂異常
at com.ray.ch10.Test.main(Test.java:7)

我們在代碼裡面加上自訂的資訊這一部分。這樣基本就可以滿足需求。

上面的代碼把輸出資料流輸入到標準錯誤流裡面,然而,我們可以通過下面的修改,把輸出部分當成普通輸出資料流來處理。

 

package com.ray.ch10;public class Test {public static void main(String[] args) {// throw new SimpleException();try {throw new SimpleException(自訂異常);} catch (SimpleException e) {e.printStackTrace(System.out);//改變的地方}}}class SimpleException extends Exception {public SimpleException() {}public SimpleException(String msg) {super(msg);}}

輸出:

 

com.ray.ch10.SimpleException: 自訂異常
at com.ray.ch10.Test.main(Test.java:7)

兩者的輸出是一樣的,但是如果我們放到ide裡面執行代碼,輸出將會變得不一樣。

 

 

 

 

聯繫我們

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