gpt4 book ai didi

java - 了解有效 Java 记录未检查异常的技巧

转载 作者:行者123 更新时间:2023-12-01 19:02:50 24 4
gpt4 key购买 nike

摘自Effective Java“记录每种方法引发的所有异常

It should be noted that documenting all of the unchecked exceptions that each method can throw is an ideal, not always achievable in the real world. When a class undergoes revision, it is not a violation of source or binary compatibility if an exported method is modified to throw additional unchecked exceptions. Suppose a class invokes a method from another, independently written class. The authors of the former class may carefully document all of the unchecked exceptions that each method throws, but if the latter class is revised to throw additional unchecked exceptions, it is quite likely that the former class (which has not undergone revision) will propagate the new unchecked exceptions even though it does not declare them.

我不明白以前的类(class)如何传播新的未经检查的异常(exception)? java 语言不强制调用者捕获和传播未经检查的异常。

最佳答案

它将精确地传播它,因为异常要么被捕获,要么被传播。如果没有捕获,则会传播异常:

public void caller() {
callee();
}

public void callee() {
throw new RuntimeException();
}

在上面的示例中,从 callee() 抛出的异常将由 caller() 方法传播,因为 caller()没有捕获它。

关于java - 了解有效 Java 记录未检查异常的技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11575708/

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