從頭認識java-10.5 棧軌跡和重新拋出異常

來源:互聯網
上載者:User

從頭認識java-10.5 棧軌跡和重新拋出異常

這一章節我們來討論一下出現異常的時候的棧軌跡和重新拋出異常。

1.棧軌跡

列印棧軌跡有兩種方式:

(1)不改變原先的代碼

 

package com.ray.ch10;public class Test {public static void main(String[] args) {try {throw new Exception(cause);} catch (Exception e) {e.printStackTrace();}}}

輸出:

 

java.lang.Exception: cause
at com.ray.ch10.Test.main(Test.java:6)

(2)自訂列印方法棧軌跡

 

package com.ray.ch10;public class Test {public static void main(String[] args) {try {throw new Exception(cause);} catch (Exception e) {for (StackTraceElement element : e.getStackTrace()) {System.out.println(element.getMethodName());System.out.println(element.getFileName());System.out.println(element.getClassName());System.out.println(element.getLineNumber());}}}}

輸出:

 

main
Test.java
com.ray.ch10.Test
6

 

我們對比一下兩個代碼塊的輸出,其實下面的那個輸出就是上面輸出的組成元素。

 

2.重新拋出異常。

有些時候我們不需要在某一層次來處理異常,特別是web應用主流的mvc結構,不同層級管理不同的東西,但是有些時候我不想在某層處理異常,那麼我需要重新拋出異常。

 

package com.ray.ch10;public class Test {private void test() throws Exception {try {throw new Exception(cause);} catch (Exception e) {throw e;}}public static void main(String[] args)  {try {new Test().test();} catch (Exception e) {e.printStackTrace();System.out.println(處理代碼);}}}

輸出:

 

java.lang.Exception: cause
at com.ray.ch10.Test.test(Test.java:7)
at com.ray.ch10.Test.main(Test.java:15)
處理代碼

 

從代碼和輸出那裡可以看見,我雖然在test方法裡面拋異常,但是我這裡不管,再扔出去到上一次,main方法裡面來處理。

 

總結:我們這一章節主要討論了棧軌跡和重新拋出異常。

 

 

 

 

聯繫我們

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