服务器之家

服务器之家 > 正文

Java异常跟踪栈定义与用法示例

时间:2021-04-30 14:29     来源/作者:chengqiuming

本文实例讲述了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

标签:

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国 2021-05-08
返回顶部