点击上方 Java后端,选择 设为星标
优质文章,及时送达
作者:北冥有只鱼
链接:segmentfault.com/a/1190000021990280
一切从Throwable开始
Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java {@code throw} statement. Similarly, only this class or one of its subclasses can be the argument type in a {@code catch} clause. ---《Throwable源码》
For the purposes of compile-time checking of exceptions, {@codeThrowable} and any subclass of {@code Throwable} that is not also a subclass of either {@link RuntimeException} or {@link Error} areregarded as checked exceptions.---《Throwable源码》
Instances of two subclasses, {@link java.lang.Error} and {@link java.lang.Exception}, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data). ------《Throwable源码》
java虚拟机栈
什么是本地方法?
栈帧
在java中,程序以一个方法为单位来开始执行。
在JVM中,每个线程都拥有一个私有的虚拟机栈,和线程同时被创建。
虚拟机栈中的元素师栈帧,存储局部变量,部分计算结果.
在方法被调用的时候被创建,在方法被调用完成时,无论方法是正常结束,
还是出现了异常或错误未执行完毕,栈帧都会被销毁.
异常信息分析
public class ExceptionDemo {
public static void main(String[] args) {
test();
}
public static void test(){
System.out.println(1 / 0);
}
}
jvm抛出了一个异常,其相关的异常信息如下:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.cxk.ExceptionDemo.test(ExceptionDemo.java:12)
at com.cxk.ExceptionDemo.main(ExceptionDemo.java:9)
这个相关的信息主要由三部分构成:
-
哪个线程中发生
-
是什么哪种类型的异常
-
程序在执行到哪一个方法的哪一行出现的异常。
下面是StackTraceElement的成员变量:
private String declaringClass;
private String methodName;
private String fileName;
private int lineNumber;
StackTraceElement被虚拟机所初始化。
Exception VS Error
检查异常(checkedException) 和 未检查异常(unCheckedException)
未检查异常: 就是RuntimeException和它的子类。
如何捕获子线程的异常
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("----------发生异常的线程名为:" + t.getName());
StackTraceElement[] stackArray = e.getStackTrace();
for (StackTraceElement stackTraceElement : stackArray) {
System.out.println("异常信息:" + stackTraceElement.toString());
}
}
}
public class ExceptionDemo {
public static void main(String[] args) {
new Thread(()->{
Thread.currentThread().setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println("--------------------------Thread Running----------------");
System.out.println(1 / 0);
}).start();
}
}
-
《The Java Virtual Machine Specification, Java SE 8 Edition》
本文分享自微信公众号 - Java后端(web_resource)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
相关文章
暂无评论...