在 Java 中,如何尝试、捕获、最终返回工作?
我无法确切地理解在 , .return
try
catch
- 如果我有并且没有,我可以放在块内。
try
finally
catch
return
try
- 如果我有 , , , ,我就不能放进去。
try
catch
finally
return
try
- 如果我有一个块,我必须把,,块的外部。
catch
return
try
catch
finally
- 如果我删除块和,我可以把块放进去。
catch
throw Exception
return
try
它们究竟是如何工作的?为什么我不能把 放在块里?return
try
代码为 , 、try
catch
finally
public int insertUser(UserBean user) {
int status = 0;
Connection myConn = null;
PreparedStatement myStmt = null;
try {
// Get database connection
myConn = dataSource.getConnection();
// Create SQL query for insert
String sql = "INSERT INTO user "
+ "(user_name, name, password) "
+ "VALUES (?, ?, ?)";
myStmt = myConn.prepareStatement(sql);
// Set the parameter values for the student
myStmt.setString(1, user.getUsername());
myStmt.setString(2, user.getName());
myStmt.setString(3, user.getPassword());
// Execute SQL insert
myStmt.execute();
} catch (Exception exc) {
System.out.println(exc);
} finally {
// Clean up JDBC objects
close(myConn, myStmt, null);
}
return status;
}
带 的代码,不带try
finally
catch
public int insertUser(UserBean user) throws Exception {
int status = 0;
Connection myConn = null;
PreparedStatement myStmt = null;
try {
// Get database connection
myConn = dataSource.getConnection();
// Create SQL query for insert
String sql = "INSERT INTO user "
+ "(user_name, name, password) "
+ "VALUES (?, ?, ?)";
myStmt = myConn.prepareStatement(sql);
// Set the parameter values for the student
myStmt.setString(1, user.getUsername());
myStmt.setString(2, user.getName());
myStmt.setString(3, user.getPassword());
// Execute SQL insert
myStmt.execute();
return status;
} finally {
// Clean up JDBC objects
close(myConn, myStmt, null);
}
}