try-with-resources 中的两个 close 方法
Two close methods in try-with-resources
我有以下代码:
try(Socket s1=new Socket(...); Socket s2=new Socket(...);)
{
some logic...
}
据我了解,Java 先关闭 s2
,然后 s1
。
如果 s2.close()
抛出异常,会发生什么? Java 会在上次失败后尝试关闭 s1
吗?
引用 JLS Sec 14.20.3(强调我的):
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources.
我有以下代码:
try(Socket s1=new Socket(...); Socket s2=new Socket(...);)
{
some logic...
}
据我了解,Java 先关闭 s2
,然后 s1
。
如果 s2.close()
抛出异常,会发生什么? Java 会在上次失败后尝试关闭 s1
吗?
引用 JLS Sec 14.20.3(强调我的):
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources.