Java 中的 try、catch、finally 中的 return 是如何工作的?

2024-01-09

我不明白到底如何return工作于try, catch.

  • 如果我有try and finally没有catch,我可以把return在 - 的里面try block.
  • 如果我有try, catch, finally,我不能放return in the try block.
  • 如果我有一个catch块,我必须把return之外的try, catch, finally blocks.
  • 如果我删除catch块和throw Exception,我可以把return在 - 的里面try block.

它们究竟是如何工作的?为什么我不能把return in the try block?

代码与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);
     }
 }

是的,这很令人困惑。

在爪哇,all非程序控制路径void功能must完成一个return,或者抛出异常。这是一条简单明了的规则。

但是,令人厌恶的是,Java 允许你放置一个extra return in a finally块,它会覆盖之前遇到的任何块return:

try {
    return foo; // This is evaluated...
} finally {
    return bar; // ...and so is this one, and the previous `return` is discarded
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 中的 try、catch、finally 中的 return 是如何工作的? 的相关文章

随机推荐