简体   繁体   English

我应该在哪里放置close()方法?

[英]Where should I put close() method?

In the following code, where should the close locate? 在以下代码中,关闭位置应该在哪里? Should it be in the try clause or in finally? 应该在try子句中还是最后? If it is finally, should it be enclosed with another try-catch? 如果最终成功,是否应将其与另一个try-catch一起使用? Thanks. 谢谢。

PrintWriter out = null;
try {
    out = new PrintWriter(
            new BufferedWriter(
                new FileWriter("out.txt", true)));
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
} finally {
    if (out != null) {
        out.close();
    }
}

See the documentation for try -with-resources . 请参阅文档try -with-resources If you're using at least Java 7, there's a nice syntax for this. 如果您至少使用Java 7,则有一个不错的语法。 Otherwise, the finally block is appropriate, since it should be closed in both the normal and exceptional cases. 否则,由于在正常情况下和例外情况下都应关闭finally块,因此该块是适当的。

Put it in the finally block. 将其放在finally块中。

Because you should close the Writer in either case (exception or no exception). 因为无论哪种情况(异常或无异常),都应关闭Writer

To handle close properly, one should ensure that it gets called whether or not an exception occurs in the main-line code, but one should also ensure that if close gets called following an exception in the main-line and then throws an exception itself, it won't cause the main-line exception to be discarded; 为了正确处理close ,应确保在主代码中是否发生异常都被调用,但也应确保如果在主代码行中的异常之后调用close ,然后自身抛出异常,它不会导致主线异常被丢弃; depending upon various factors including whether the object was open for reading or writing, it may be desirable to either let the main-line exception percolate up (perhaps encapsulating information about the close failure), log or encapsulate the main-line exception but have the close failure percolate up, or throw a "double fault" exception which encapsulates both of the others. 取决于各种因素(包括对象是为读取还是写入而打开的),可能希望让主线异常渗透(也许封装有关关闭失败的信息),记录或封装主线异常,但具有close失败会渗透,或者引发“双重错误”异常,从而封装其他两个异常。

The try-with-resources feature of Java 7 provides pretty good behavior for many scenarios: if an exception occurs in try and another in close , the latter exceptions get added to a list of suppressed exceptions (which exception-handling code should look for). Java 7中的尝试-以资源功能提供了多种场景相当不错的表现:如果发生异常try另一个在close ,后者例外被添加到抑制例外列表(应该找哪个异常处理代码) 。 If a method is supposed to grab data from a wireless sensor and write it to a file, and if the caller will expect that in the event of sensor trouble the file will hold as much information as was read successfully, then a failure to close the file may be more important than a sensor failure [if the sensor eg only includes "return oldest item" and "delete oldest item" commands, then if the file closed properly an exception during sensor communication would mean that any data which was no longer in the sensor would be in the file. 如果应该使用一种方法从无线传感器中获取数据并将其写入文件,并且调用方希望在发生传感器故障的情况下文件将保存与成功读取的信息一样多的信息,则无法关闭文件。文件可能比传感器故障更重要[如果传感器例如仅包括“返回最旧的项目”和“删除最旧的项目”命令,则如果文件正确关闭 ,则在传感器通信期间出现异常将意味着不再包含任何数据。传感器将在文件中。 If the file didn't close properly, that would imply that there might have been permanent data loss, and someone should be told about it. 如果文件未正确关闭,则意味着可能存在永久性数据丢失,应告知某人。

Code to handle the "sensor capture" scenario would end up being a bit icky: the sensor read logic would be placed within a try block whose finally would capture any exception to a variable. 处理“传感器捕获”场景的代码最终会变得有些棘手:传感器读取逻辑将放置在try块中, tryfinally将捕获变量的任何异常。 The finally block would then have to use its own try block for the close; 然后, finally块将不得不使用其自己的try块进行关闭; if an exception occurs there, throw a custom writeFileCloseFailure exception which encapsulates both the exception (if any) from the try block and the exception from the close ; 如果在那里发生异常,则抛出一个自定义的writeFileCloseFailure异常,该异常封装了try块中的异常(如果有的话)和close的异常; otherwise, rethrow the exception (if any) from the try block. 否则,请从try块中抛出异常(如果有)。 Note that since ioException could represent either a failure to get data from the sensor (somewhat expected and tolerable) or a failure to write the file (very bad), wrapping in another exception type would allow the caller to distinguish those conditions. 请注意,由于ioException可能表示无法从传感器获取数据(有些期望并且可以忍受)或无法写入文件(非常不好),因此包装为另一种异常类型将允许调用方区分这些条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM