gpt4 book ai didi

java - 默认异常处理程序如何工作

转载 作者:行者123 更新时间:2023-11-30 08:18:12 25 4
gpt4 key购买 nike

当我们尝试运行下面的程序时,我们会得到这样的错误:Exception in thread "main"java.lang.ArithmeticException:/by zero

class excp {
public static void main(String args[]) {
int x = 0;
int a = 30/x;
}
}

但是当我们问某人这些是如何工作的时,然后他告诉我这个异常被默认的异常处理程序捕获,所以我无法理解这个默认的异常处理程序是如何工作的。请详细说明。

最佳答案

引用 JLS 11:

30/x - 违反了 Java 语言的语义约束 - 因此会发生异常。

If no catch clause that can handle an exception can be found, 
then the **current thread** (the thread that encountered the exception) is terminated

终止前 - 未捕获的异常按照以下规则处理:

(1) If the current thread has an uncaught exception handler set, 
then that handler is executed.

(2) Otherwise, the method uncaughtException is invoked for the ThreadGroup
that is the parent of the current thread.
If the ThreadGroup and its parent ThreadGroups do not override uncaughtException,
then the default handler's **uncaughtException** method is invoked.

在你的情况下:

异常后进入Thread类

     /**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}

然后它根据规则 2 转到 ThreadGroup uncaugthException - 由于没有定义异常处理程序它转到 Else 如果 - 并且线程终止

public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} **else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}**
}
}

关于java - 默认异常处理程序如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27664104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com