Connection conn = null; try {
conn = dataSource.getConnection();
// 执行数据库操作
} catch (SQLException e) {
// 异常处理
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// 日志记录
}
}
}
public int testReturn() {
try {
System.out.println("try block");
return 1;
} finally {
System.out.println("finally block");
return 2;
}
}
FileInputStream fis = null; try {
fis = new FileInputStream("app.log");
// 处理文件内容
} catch (IOException e) {
System.out.println("文件读取失败");
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.out.println("文件关闭异常");
}
}
}
FileInputStream fis = null; Connection conn = null; HttpURLConnection httpConn = null;
try {
fis = new FileInputStream("data.txt");
// 文件处理逻辑
try {
conn = dataSource.getConnection();
// 数据库操作
try {
httpConn = (HttpURLConnection) new URL("http://api.service.com").openConnection();
// 网络请求
} finally {
if (httpConn != null) {
httpConn.disconnect();
}
}
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("数据库连接关闭异常");
}
}
}
} catch (Exception e) {
System.out.println("处理过程异常");
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.out.println("文件流关闭异常");
}
}
}
public boolean processOrder(Order order) {
Connection conn = null;
boolean success = false;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
// 扣减库存
reduceInventory(conn, order.getItems());
// 创建订单记录
createOrderRecord(conn, order);
// 生成支付流水
createPaymentFlow(conn, order);
conn.commit();
success = true;
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
log.error("回滚失败", ex);
}
}
log.error("订单处理异常", e);
} finally {
if (conn != null) {
try {
conn.setAutoCommit(true);
conn.close();
} catch (SQLException e) {
log.error("连接关闭异常", e);
}
}
}
return success;
}
// 脆弱的写法 try {
acquireLock();
doBusiness();
} catch (Exception e) {
releaseLock(); // 如果发生Error,锁不会释放
throw e;
}
// 健壮的写法
try {
acquireLock();
doBusiness();
} finally {
releaseLock(); // 无论发生什么,锁都会释放
}