服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java异常跟踪栈定义与用法示例

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

2021-04-30 14:29chengqiuming Java教程

这篇文章主要介绍了Java异常跟踪栈定义与用法,结合具体实例形式分析了异常处理栈的概念、原理及相关使用技巧,需要的朋友可以参考下

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

延伸 · 阅读

精彩推荐