Java - 如果发生异常,连接/流是否已经关闭以及如何正确处理?

标签 java exception connection inputstream ioexception

我想知道,如果我的代码中有某种应关闭以释放资源的连接或流,这对连接实例本身意味着什么?

代码示例:

CustomConnection connection;
try{
    connection = //some code that opens a connection
    //some code using the connection
}catch(IOException){
    //Some logging and Handling of IOExceptions
}finally{
    //resources cleanup
    try{
        connection.close();
    }catch(IOException){
        //Some Logging
        //What else should be done here?
        //Is my Connection closed at this point and can I just move on?
        //Or should there be anything else done here 
        //to ensure that the connection is actually closed?
    }
}

例如,如果我有一个打开的 TCP 连接到 SQL 服务器,但我无法关闭它,因为服务器已崩溃或我的设备无法再访问该设备。显然我会得到一个 IO,或者在本例中得到一个 SQLException。如果是这样:

  1. 我应该考虑资源或套接字实际上有 benn 被释放了?
  2. JVM 或操作系统会超时处理吗? (操作系统最终可能会这样做,但在这种情况下,这实际上是一个好的编程实践)
  3. 我应该尝试自己解决这个问题

编辑1:我知道“尝试使用资源”的结构。我只是想知道如果我使用的连接没有实现 AutoCloseable,如何处理连接关闭。

最佳答案

我会让 CustomConnection 实现 AutoClosable 接口(interface),以便它可以在 try-with-resources 语句中使用:

try (CustomConnection connection = ...) {

} catch (IOException e) {
    // connection is not in scope here, and it is closed.
}

来自 Oracle 的 try-with-resources tutorial ,它指出:

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

使用它来回答您的问题,您的资源将在输入 catchfinally block 时关闭。

<小时/>

如果初始化连接可能引发异常,则必须注意被抑制的异常:

An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents, an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

关于Java - 如果发生异常,连接/流是否已经关闭以及如何正确处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53378962/

相关文章:

c# - 一段时间后生物识别设备 ping 失败

c# - WPF 中的 SwingUtilities.invokeLater 等价物

Java OpenCV - 使用 knnMatch 和 findHomography 显示重复项

java - Android 开发从标记纬度和经度系统地设置目的地

Java - 当外部类捕获异常时进行监听

java - 将java值插入sqlite数据库

java - 是否有可能检测到输出的去向 - 终端或管道/文件?

java - Java 中的嵌套异常

java - 如何在 Servlet 中使用 UncaughtExceptionHandler

java - 当我尝试为 Oracle 数据库创建 Connection 对象时,为什么会出现此 SQLException(没有合适的驱动程序)?