Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does return work in try, catch, finally in Java?

I can't understand exactly how return works in try, catch.

  • If I have try and finally without catch, I can put return inside the try block.
  • If I have try, catch, finally, I can't put return in the try block.
  • If I have a catch block, I must put the return outside of the try, catch, finally blocks.
  • If I delete the catch block and throw Exception, I can put the return inside the try 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);      }  } 
like image 473
elvis Avatar asked Jun 26 '18 07:06

elvis


People also ask

Can you return in a try catch Java?

In a try-catch-finally block that has return statements, only the value from the finally block will be returned. When returning reference types, be aware of any updates being done on them in the finally block that could end up in unwanted results.

Can we use return statement in try catch or finally block?

Yes, we can write a return statement of the method in catch and finally block.

Does finally execute if you return in try?

Java For TestersYes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.

Where do I return my try catch finally?

In the preceding code, finally block overrides the value returned by try block. Therefore, this would return value 50 because the value returned by try has been overridden by finally block.


2 Answers

Yes, it's confusing.

In Java, all program control paths of a non-void function must finish with a return, or throw an exception. That's the rule put nice and simply.

But, in an abomination, Java allows you to put an extra return in a finally block, which overrides any previously encountered return:

try {     return foo; // This is evaluated... } finally {     return bar; // ...and so is this one, and the previous `return` is discarded } 
like image 176
Bathsheba Avatar answered Oct 11 '22 18:10

Bathsheba


Finally block will always execute even if we caught the exception in catch block or even our try block executed as expected.

so when does finally block will be execute with in the flow...

if we have return statement inside the try/catch block then before executing the return statement finally block will be executed (like as for closing the connection or I/O)

function returnType process() {   try {       // some other statements       // before returning someValue, finally block will be executed       return someValue;   } catch(Exception ex) {      // some error logger statements      // before returning someError, finally block will be executed      return someError;   } finally {     // some connection/IO closing statements     // if we have return inside the finally block     // then it will override the return statement of try/catch block     return overrideTryCatchValue;   } } 

but if you have return statement inside the finally statement then it will override the return statement inside the try or catch block.

like image 40
pramesh Avatar answered Oct 11 '22 17:10

pramesh