gpt4 book ai didi

Java 1.5 兼容模式将处理所有可能的异常,无一异常(exception)地吞噬/丢失和资源关闭?

转载 作者:行者123 更新时间:2023-11-29 03:27:40 25 4
gpt4 key购买 nike

我有一些方法使用一些应该在最后关闭的资源,方法本身和资源关闭可能会抛出所有内容,包括 IO Connection 等等异常,一些运行时异常甚至错误(继承 Throwable OOM 的一切通常是case.).我想在不丢失信息的情况下处理所有异常,并向客户端发送/抛出最重要的异常(假设是运行时异常/错误?)这是我使用的模式(它是 java 1.5,所以我不能使用1.7 的资源特性):

Throwable thr=null;
try {
methodThatCouldThrowCheckedExceptionAndErrorAndRuntimeExcpetion();
log("method succesfully executed.");
} catch (IKnowThisException ikte) {
//Exception will be not lost
log("Method was not executed ,and I can suggest further actions",itke);
thr=ikte;
} catch (Throwable t) {
// This exception will be not lost too
log("Method was not executed ,and I don't know why.",t);
thr=t;
} finally {
try{
// The method below - of course contains the standard null checkers.
closeResourcesMethodThatCouldThrowEverythingToo();
log("resources were closed.");
} catch (IKnowThisEscpetionToo iktet) {
log(iktet);
throw new IllegalStateException("Resources were not closed , because of the known exception and I can suggest some actions" , ijtet);
} catch (Throwable t) {
log(t);
throw new IllegalStateException("Resources were not closed and I don't know why" , t);
}
// in case resources are closed we can re-throw exception from try{} block
if ( thr != null ) {
throw thr;
}
}

但我不完全确定这是最好的方法 .Here a similar approach i sused .但它不处理未经检查的异常(我需要处理它们吗?)是否存在我可能会丢失有值(value)信息的情况?在大多数示例中,我发现没有对 Errors/RuntimeExcpetions 做任何特别的事情,但我希望它们被记录下来。有更好的方法吗?也许我应该构造一个更复杂的链式异常来保持信息紧凑?

最佳答案

要保留所有错误,最好使用自定义异常类,它提供类似于 ARM 的“抑制异常”集合的东西。

如果该方法抛出异常,则这是主要异常的(原因)。如果关闭资源引发额外的异常,它们将作为被抑制的异常添加到 main 中。

如果方法没有失败完成,但关闭资源引发异常,第一个成为主要异常,后续资源关闭失败作为抑制异常添加到它。

如果资源旨在产生写入文件或更新数据库等副作用,则应用程序需要确定在关闭该资源失败时要执行的操作。使用隐藏那些资源关闭异常的通用机制将不允许应用程序做出该决定,并且仅在应用程序不关心是否实际生成任何输出的极少数情况下才有用。

关于Java 1.5 兼容模式将处理所有可能的异常,无一异常(exception)地吞噬/丢失和资源关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20197742/

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