【发布时间】:2018-09-10 11:49:50
【问题描述】:
我知道,即使发生异常,也总是会执行 finally 块。
如果我们在 try 或 catch 块中使用 System.exit(0) 它不会执行;
用于释放资源。
但我有疑问,catch 块之后的语句无论如何都会执行,即使这些语句没有 finally 编写,对吧?
请解释一下。
见下面代码sn-ps -
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?
【问题讨论】:
标签: java