说明
使用场景: 在一个java方法结束时(包括正常结束或者异常情况),都会执行一段java代码,例如:在一个方法中出现多处异常处理块,每个处理快互相不嵌套,需要在发生异常时在catch{}中释放资源,可以统一在最后释放。
例子:使用jdbc连接数据库
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.entity.User;
public class UserDao {
private Connection con = null;
public UserDao() {
// TODO Auto-generated constructor stub
try {
Class.forName("");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("加载JDBC驱动失败异常");
e.printStackTrace();
}
String url = "";
String user = "";
String password = "";
try {
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Connection对象创建失败异常");
e.printStackTrace();
}
}
// 创建数据库连接
public boolean login(User user) {
System.out.println("UserDao" + user.toString());
Statement st = null;
ResultSet res = null;
boolean b = false;
try {
try {
st = this.con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Statement对象创建失败异常");
e.printStackTrace();
}
String sql = "select * from user where name= '" + user.getName() + "' and password= '" + user.getPassword()
+ "'";
System.out.println(sql);
try {
res = st.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("ResultSet对象创建失败异常");
e.printStackTrace();
}
try {
b = res.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("ResultSet判断元素出现异常");
e.printStackTrace();
}
} finally {
System.out.println("结束块");
try {
if(res!=null){
res.close();
}
if(st!=null){
st.close();
}
if(con!=null){
this.con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("关闭资源异常");
e.printStackTrace();
}
}
return b;
}
}
说明:
try {
//可能多处出现异常的部分
} finally {
//结束部分
}