[英]Handle exception without try/catch
I have got a method where the exceptions thrown have to be handled by the caller, and not by the method itself (exceptions specified in the signature and not in the body). 我有一个方法,抛出的异常必须由调用方处理,而不是由方法本身处理(签名中指定的异常,而不是主体中指定的异常)。 However, in case of something bad happening, I would like to use something similar to a
finally
statement to close my reader before the caller has to deal with the problem. 但是,如果发生了一些不好的情况,我想在调用者不得不处理该问题之前,使用类似于
finally
语句的方法来关闭我的阅读器。
In the current configuration, if an exception is triggered, the reader remains open. 在当前配置中,如果触发了异常,则读取器保持打开状态。
private static void executeFile(Connection c, String fileName) throws SQLException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.defaultCharset())); // $JL-I18N$
/*
Lot of stuff happen here, and might trigger exceptions
*/
reader.close();
}
Is there a way to handle this case ? 有没有办法处理这种情况? Or should the method be refactored to handle exceptions by itself ?
还是应该重构该方法以单独处理异常?
EDIT 编辑
Some good tips have been provided in the comments. 评论中提供了一些很好的技巧。 The solution I finally chose considering this was to extract the code triggering the warning and using a try-with-resources.
我最终选择考虑的解决方案是提取触发警告的代码并使用try-with-resources。
This is how you do it. 这就是你的做法。 Use try-with-resources.
使用try-with-resources。
private static void executeFile(Connection c, String fileName)
throws SQLException, IOException {
try (InputStream is = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr)) {
/* Lots of stuff */
}
}
Exceptions thrown in the try block will be propagated, and the reader stack will be closed. 在try块中引发的异常将被传播,并且阅读器堆栈将被关闭。 If (hypothetically) the implicit
close()
performed by the try-with-resource was to throw an exception: 如果(假设)由try-with-resource执行的隐式
close()
抛出异常:
Note that I have rewritten ` 注意,我已经重写了`
new InputStreamReader(is, Charset.defaultCharset())
as 如
new InputStreamReader(is)
because they are equivalent: check the javadoc. 因为它们是等效的:请检查javadoc。 The other rewriting was solely for readability, though it does illustrate that try-with-resources can manage multiple resources.
另一个重写只是为了提高可读性,尽管它确实说明了“尝试使用资源”可以管理多个资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.