I can't understand exactly how return
works in try
, catch
.
- If I have
try
andfinally
withoutcatch
, I can putreturn
inside thetry
block. - If I have
try
,catch
,finally
, I can't putreturn
in thetry
block. - If I have a
catch
block, I must put thereturn
outside of thetry
,catch
,finally
blocks. - If I delete the
catch
block andthrow Exception
, I can put thereturn
inside thetry
block.
How do they work exactly? Why I can't put the return
in the try
block?
Code with 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;
}
Code with try
, finally
without 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);
}
}
return
insidetry-catch
ortry-catch-finally
. Consider this question as well. – Russotry
block, but you need to make sure you also return something in all thecatch
blocks. Other than that, just take note of what Bathsheba mentioned. This is essentially the same debate on single exit point - whether it is bad to return in anif
block. – Resentfultry
block, by all means, return from insidetry
. Do not widen the scope of the variable you want to return. That would be bad design (keep scopes as small as possible). – Blategoto
for cleanup. I can't think of a good reason to return from finally though. I think that was a mistake in the language design to allow that. – Navarrete