Selasa, 15 Maret 2016

Return statement in finally block in java

Can we write return statement in finally block

  • Finally block will executes always excepts system.exit().
  • So if we are returning some value in finally means it will be returned always
  • Finally will executed so method always returns finally return value and no need of keeping return value at end of the method.
  • And in finally after return if we keep some statement those statement will be treated as dead code.



i)Return statement in finally block
  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){ 
  6.         
  7. try {
  8.  

  9.  
  10. } catch (Exception e) {
  11.  
  12. }
  13.  finally(){
  14.  return 1;
  15. }   
  16.  System.out.println("End of the method"); // Error : Unreachable code
  17. }
  18.     
  19.     
  20. public static void main(String[] args) {
  21.         
  22.         TryCatchReturn obj = new TryCatchReturn();
  23.        
  24.  
  25. }

  26. }
     
ii) return statement in finally



  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){ 
  6.         
  7. try {
  8.  

  9.  
  10. } catch (Exception e) {
  11.  
  12. }
  13.  finally(){
  14.  return 1;
  15. System.out.println("End of the method"); // Error : Unreachable code
  16. }   
  17.  
  18. }
  19.     
  20.     
  21. public static void main(String[] args) {
  22.         
  23.         TryCatchReturn obj = new TryCatchReturn();
  24.        
  25.  
  26. }

  27. }
     
iii) return statement in try catch and finally blocks



  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){ 
  6.         
  7. try {
  8.  
  9. return 10;
  10.  
  11. } catch (Exception e) {
  12.  return 20;
  13. }
  14.  finally(){
  15.  return 30;
  16. }   
  17.  
  18. }
  19.     
  20.     
  21. public static void main(String[] args) {
  22.         
  23.  TryCatchReturn obj = new TryCatchReturn();
  24.        
  25.  System.out.println(obj.calc())
  26. }

  27. }



Output:


  1. 30

finally with return statement in java

Bagikan

Jangan lewatkan

Return statement in finally block in java
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.