本文實例講述了java異常跟蹤棧定義與用法。分享給大家供大家參考,具體如下:
一、異常跟蹤棧簡介
異常對象的printstacktrace方法用于打印異常的跟蹤棧信息,根據printstacktrace方法的輸出結果,我們可以找到異常的源頭,并跟蹤到異常一路觸發的過程。
二、main方法中異常跟蹤棧的應用
1 代碼示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
class selfexception extends runtimeexception { selfexception(){} selfexception(string msg) { super (msg); } } public class printstacktracetest { public static void main(string[] args) { firstmethod(); } public static void firstmethod() { secondmethod(); } public static void secondmethod() { thirdmethod(); } public static void thirdmethod() { throw new selfexception( "自定義異常信息" ); } } |
2 運行結果
exception in thread "main" selfexception: 自定義異常信息
at printstacktracetest.thirdmethod(printstacktracetest.java:26)
at printstacktracetest.secondmethod(printstacktracetest.java:22)
at printstacktracetest.firstmethod(printstacktracetest.java:18)
at printstacktracetest.main(printstacktracetest.java:14)
3 結果分析
只要異常沒有被完全捕獲,異常從發生異常的方法逐漸向外傳播,首先傳給該方法的調用者,該方法調用者再次創給其調用者……直至最后傳到 main方法,如果main方法依然沒有處理該異常,jvm會中止該程序,并打印異常的跟蹤棧信息。
三、多線程中異常跟蹤棧的應用
1 代碼示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class threadexceptiontest implements runnable { public void run() { firstmethod(); } public void firstmethod() { secondmethod(); } public void secondmethod() { int a = 5 ; int b = 0 ; int c = a / b; } public static void main(string[] args) { new thread( new threadexceptiontest()).start(); } } |
2 運行結果
exception in thread "thread-0" java.lang.arithmeticexception: / by zero
at threadexceptiontest.secondmethod(threadexceptiontest.java:16)
at threadexceptiontest.firstmethod(threadexceptiontest.java:10)
at threadexceptiontest.run(threadexceptiontest.java:6)
at java.lang.thread.run(thread.java:619)
3 結果分析
程序在thread的run方法中出現了arithmeticexception異常,這個異常的源頭是threadexception的secondmethod方法,位于文件16行。這個異常傳播到thread類的run方法就會結束。
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://blog.csdn.net/chengqiuming/article/details/70139255