我知道,即使发生异常,也始终会执行 finally 块。
如果我们在 try 或 catch 块中使用 System.exit(0) 它不会执行;
它用于释放资源。
但我有一个问题,即使没有 finally 写入,catch 块之后的语句也会执行,对吗?
请解释一下。
请参阅以下代码片段 -
public static void main(String[] args) throws SQLException {
Connection con=null;
try {
String url ="someURL";
String user ="someUserName";
String password ="somePassword";
con=DriverManager.getConnection(url, user, password);
.
.
.
} catch(Exception e) {
e.printStackTrace();
} finally {
if(con!=null) {
con.close();
}
}
}
和
public static void main(String[] args) throws SQLException {
Connection con=null;
try {
String url ="someURL";
String user ="someUserName";
String password ="somePassword";
con=DriverManager.getConnection(url, user, password);
.
.
.
}catch(Exception e) {
e.printStackTrace();
}
if(con!=null) {
con.close();
}
}
所以我的con.close();意志无论如何都会执行,那为什么我需要finally?
慕田峪9158850
阿晨1998
相关分类