gpt4 book ai didi

java - 重新抛出已检查的异常

转载 作者:行者123 更新时间:2023-12-02 08:50:55 25 4
gpt4 key购买 nike

public void foo() {
begin();
try {
...
commit();
} catch (Exception e) {
rollback();
throw e;
}
}

在上面的示例中,由于 foo 没有 throws Exception,因此出现错误。添加这一点也不会使该方法的可用性变得很好。

最好的方法是什么?如果发生错误而没有真正“处理”错误,您该如何处理?

最佳答案

从 Java 8 开始我们使用

/**
* Cast a CheckedException as an unchecked one.
*
* @param throwable to cast
* @param <T> the type of the Throwable
* @return this method will never return a Throwable instance, it will just throw it.
* @throws T the throwable as an unchecked throwable
*/
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
<小时/>

您可以重新抛出检查异常,但只能通过避免编译器检查异常验证来实现。

public void foo() throws MyCheckedException {
begin();
try {
...
commit();
} catch (Exception e) {
rollback();
// same as throwing an exception without the compiler knowing.
Thread.currentThread().stop(e);
}
}

在使用 stop() 之前,您应该阅读 http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

Thread.currentThread().stop(e) .. is behaviorally identical to Java's throw operation, but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw:

关于java - 重新抛出已检查的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4554230/

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