gpt4 book ai didi

java - 当 try block 中的多行抛出异常时,使用 Try-With-Resources 而不是 finally block

转载 作者:行者123 更新时间:2023-12-01 06:42:29 26 4
gpt4 key购买 nike

代码片段:

InputStream inputStream = null;
try{
ExternalServiceObject object = externalService.getObject();
inputStream = object.getInputStream();
// further uses of inputStream
} catch(Exception e){
throw e;
} finally {
if(inputStream != null)
inputStream.close();
}

这里,externalService.getObject()也可以抛出异常。

希望使用 try-with-resources 重构此代码,从而避免使用 finally block 。或者说现在的行为是最合适的行为。

感谢所有评论和回答。

最佳答案

如果您不需要外部服务对象来做其他事情:

try (InputStream inputStream = externalService.getObject().getInputStream()) {
// further uses of inputStream
} catch (Exception e) {
// ... logging etc
throw e;
}

关于java - 当 try block 中的多行抛出异常时,使用 Try-With-Resources 而不是 finally block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48121856/

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