Return in try catch finally in java

Содержание
  1. Java finally block when return statement is encountered
  2. Finally: Example with return statement
  3. Does finally block Override the values returned by try-catch block?
  4. Top Related Articles:
  5. About the Author
  6. 4. Valid Cases with correct return statements :
  7. 4.1 Write return statement after completion of try-catch-finally blocks; that is just before end of method
  8. Reason:
  9. 4.2 Write return statement inside finally-block only; but there shouldn’t be any statement after finally-block
  10. Reason:
  11. 4.3 Write return statement inside both try-block & catch-block; there is no compulsion to write return inside finally-block and this completely optional (Case 6)
  12. Reason:
  13. 4.4.1 Write return statement inside try-block & at the end of method; that is just before end of method
  14. Reason:
  15. 4.4.2 Write return statement inside both try-block & finally-block; but no statement after finally block
  16. Reason:
  17. 4.4.3 Write return statement inside both try-block & finally-block; but no statement after finally block (no catch block for this case)
  18. Reason:
  19. 4.5.1 Write return statement inside catch-block & at the end of method; that is just before end of method
  20. Reason:
  21. 4.5.2 Write return statement inside both catch-block & finally-block; but no statement after finally-block
  22. Reason:
  23. 4.6 Write return statement inside try-block & catch-block & finally-block; but return value from try-block or catch-block will be overridden by return statement in the finally-block
  24. Reason:
  25. 4.7 Conclusion for Valid case:
  26. 5. Invalid Cases with incorrect return statements :
  27. 5.1 returns value from try-block only
  28. 5.2 returns value from catch-block only
  29. 5.3 returns value from try-catch-finally blocks; but contains some statements after finally-block
  30. 5.4 returns value from finally-block only; but contains some statements after finally block
  31. 5.5 Conclusion for Invalid cases:
  32. 6. Final Conclusion:
  33. Related Articles:
  34. References:
Читайте также:  Display messages in java

Java finally block when return statement is encountered

In my last tutorial, we discussed about finally block, which is used with a try block and always execute whether exception occurs or not. Here we will see few examples to understand the behaviour of finally block when a return statement is encountered in try block.

Lets see this code snippet, What do you think? Will finally would execute even if there is a return statement in try block as well as in catch block?

try < //try block . return success; >catch (Exception ex) < //catch block . return failure; >finally

The answer is yes. finally block will execute. The only case where it will not execute is when it encounters System.exit().

Finally: Example with return statement

class FinallyDemo < public static int myMethod() < try < //try block return 0; >finally < //finally System.out.println("Inside Finally block"); >> public static void main(String args[]) < System.out.println(FinallyDemo.myMethod()); >>

Does finally block Override the values returned by try-catch block?

Yes. Finally block overrides the value returned by try and catch blocks, lets take an example to understand this:

public static int myTestingFuncn() < try< . return 5; >finally < . return 19; >>

This program would return value 19 since the value returned by try has been overridden by finally.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

4. Valid Cases with correct return statements :

4.1 Write return statement after completion of try-catch-finally blocks; that is just before end of method

Reason:

  • This is valid case because after try-catch-finally block execution, method returns value
  • Also, it can be seen as 2 independent entities with,
  • 1 st being try-catch-finally block
  • 2 nd is return statement after try-catch-finally block

4.2 Write return statement inside finally-block only; but there shouldn’t be any statement after finally-block

Reason:

  • whether any exception is raised or NOT from try-block
  • and its corresponding exception is being handled or NOT in the catch-block
  • finally-block will always be executed irrespective of the program’s outcome
  • except in one scenario when System.exit(0); is invoked explicitly
  • Error-scenario : any statement after finally block will result in compile-time error stating “Unreachable code

4.3 Write return statement inside both try-block & catch-block; there is no compulsion to write return inside finally-block and this completely optional (Case 6)

Reason:

  • Whenever try-block executes successfully, then it can return value for this method
  • Also, if any exception is raised from try-block then its corresponding exception will be caught in the catch-block
  • And from catch-block also, it can return value for this method
  • Error-scenario : any statement after finally block in this example, will result in compile-time error stating “Unreachable code

4.4.1 Write return statement inside try-block & at the end of method; that is just before end of method

Reason:

  • Whenever try-block executes successfully, then it can always return value for this method
  • But if any exception is raised & it is handled in the corresponding catch-block –> return statement at the end of method will be executed and returns the value for this method after executing finally-block
  • Error-scenario : any statement after return statement at the end of method, will result in compile-time error stating “Unreachable code

4.4.2 Write return statement inside both try-block & finally-block; but no statement after finally block

Reason:

  • Whenever try-block executes successfully, then it can always return value for this method
  • But if any exception is raised & it is handled in the corresponding catch-block –> return statement inside finally-block will return value for this method (after executing any statement inside finally-block before encountering return statement)
  • Error-scenario : any statement after return statement (i.e.; finally-block in this case) will result in compile-time error stating “Unreachable code

4.4.3 Write return statement inside both try-block & finally-block; but no statement after finally block (no catch block for this case)

Reason:

  • This case is very similar to Case 4.B but it has got no catch block in try-catch-finally blocks sequence
  • So, whenever try-block executes successfully, then it can always return value for this method from try-block
  • But if any exception is raised then it is NOT handled as there is no catch-block for this case
  • So, whenever exception is raised then JVM checks for handler-code up in the runtime stack & finally-block gets executed to return value (after executing any statement inside finally-block before encountering return statement)
  • Error-scenario : any statement after return statement (i.e.; finally-block in this case) will result in compile-time error stating “Unreachable code

4.5.1 Write return statement inside catch-block & at the end of method; that is just before end of method

Reason:

  • Whenever try-block executes successfully, then it can always return value from end of method
  • If any exception is raised from try-block then it get caught in the corresponding catch-block and catch-block can also return value
  • But if any exception is raised & it is handled in the corresponding catch-block –> return statement at the end of method will be executed and returns value for this method after executing finally-block
  • Error-scenario : any statement after return statement at the end of method, will result in compile-time error stating “Unreachable code

4.5.2 Write return statement inside both catch-block & finally-block; but no statement after finally-block

Reason:

  • Whenever try-block executes successfully, then it can always return value from finally-block
  • If any exception is raised from try-block then it is get caught in the corresponding catch-block and catch-block can also returns value
  • But if any exception is raised & it is handled in the corresponding catch-block –> return statement inside finally-block will return value for this method (after executing any statement inside finally-block before encountering return statement)
  • Error-scenario : any statement after return statement (i.e.; finally-block) will result in compile-time error stating “Unreachable code

4.6 Write return statement inside try-block & catch-block & finally-block; but return value from try-block or catch-block will be overridden by return statement in the finally-block

Reason:

  • Whenever try-block executes successfully, then it can return value for this method from try-block
  • Similarly, if any exception is raised then exception gets caught in the catch-block & it can also return value (from catch-block)
  • Since, we have finally-block returning value therefore returning value from try-blockorcatch-block will be overridden by return statement in the finally-block
  • Because, on all cases finally-block gets executed irrespective of exception is raised or NOT from try-block and it is handled or NOT inside catch-block.
  • Therefore, overrides any return value from try-block or catch-block
  • This is called overridden case
  • Error-scenario : any statement after finally block in this example, will result in compile-time error stating “Unreachable code

4.7 Conclusion for Valid case:

  • Above 9 examples are valid cases to write return statement;
  • except these 9 example mentioned in the above cases, all other cases results in compile-time error
  • following examples depicts few of those cases

Let us see some compile-time error for invalid cases

5. Invalid Cases with incorrect return statements :

  1. returns value from try-block only
  2. returns value from catch-block only
  3. returns value from try-catch-finally blocks; but contains some statements after finally-block
  4. returns value from finally-block only; but contains some statements after finally block

5.1 returns value from try-block only

  • Compile-time error: This method must return a result of type int

5.2 returns value from catch-block only

  • Compile-time error: This method must return a result of type int

5.3 returns value from try-catch-finally blocks; but contains some statements after finally-block

5.4 returns value from finally-block only; but contains some statements after finally block

5.5 Conclusion for Invalid cases:

  • Any code present after finally-block will results compile-time error stating “Unreachable code
  • Similarly, any code after return statement will results compile-time error stating “Unreachable code

6. Final Conclusion:

Out of all possible valid cases,

  • If a method contains a finally-block
  • then finally-block will always gets executed
  • irrespective of any valid combination used in the program

In the next article, we will see detail example on return statement with finally block

  • Java – Exception Handling
  • Java – Exception Hierarchy
  • Java – 5 important keywords in Java Exception handling
  • Java – Runtime mechanism, what happens when exception is thrown ?
  • Java – Checked Exception v/s Unchecked Exception
  • Java – Exception propagation
  • Java – try-catch block
  • Java – finally block
  • Java – try with multiple catch blocks
  • Java – Nested try-catch block
  • Java – Returning value from method having try-catch-finally blocks
  • Java – return statement with finally block
  • Java – final v/s finally v/s finalize
  • Java – Various methods to print exception information
  • Java – throw keyword
  • Java – throws keyword
  • Java – throw v/s throws
  • Java – Difference between throws clause and try-catch-finally block
  • Java – Rules for Exception handling w.r.t Method Overriding
  • Java – User-defined or Custom exception
  • Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
  • Java – Top Exception and Error
  • Java – Interview question and answers on Exception Handling
  • Java 7 – try with resources
  • Java 7 – multi-catch block

References:

  • https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
  • https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
  • https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
  • https://docs.oracle.com/javase/tutorial/essential/exceptions/
  • https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
  • https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
  • https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
  • https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
  • https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
  • http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
  • http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
  • http://otfried.org/courses/cs206/slides/slides-stackframes.pdf

Happy Coding !!
Happy Learning !!

Источник

Оцените статью