Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By jim829

Thread: How does 'finally' block ensure tht code which could b bypassed by 'return' executes?

  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default How does 'finally' block ensure tht code which could b bypassed by 'return' executes?

    The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
    source

    But how could that ever happen? Because if any statement is unreachable (i.e. susceptible to being bypassed by a return, continue or break), the compiler complains that it is unreachable, as you can see in the following programs.

    Can you give me an example if there is any possible scenerio of any code being bypassed by a continue, break or return?

    1.
    Java Code:
    class Test {
    	
    	public static void main (String [] args) {
    		alpha();
    	}
    
            private static void alpha() {
    		String [] stringArray = {"a", "b", "c"};
    		for (String string : stringArray) {
    			System.out.println("Printing... ");
    		}
    		return;
    		System.out.println("After return.");//*************COMPILER COMPLAINS
    	}
    }
    2.
    Java Code:
    class Test {
    	
    	public static void main (String [] args) {
    		alpha();
    	}
    
            private static void alpha() {
    		String [] stringArray = {"a", "b", "c"};
    		for (String string : stringArray) {
    			System.out.println("Printing... ");
    			break;
    			System.out.println(string);//*********COMPILER COMPLAINS
    		}
    	}
    }
    3.
    Java Code:
    class Test {
    	
    	public static void main (String [] args) {
    		alpha();
    	}
    
            private static void alpha() {
    		String [] stringArray = {"a", "b", "c"};
    		for (String string : stringArray) {
    			System.out.println("Printing... ");
    			continue;
    			System.out.println(string);//*********COMPILER COMPLAINS
    		}
    	}
    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: How does 'finally' block ensure tht code which could b bypassed by 'return' execu

    Java Code:
    public void someMethod() {
        SomeResource resource = getSomeResource();
        try {
            someOtherMethodThatMayThrowAnException();
        } finally {
            handBackResource(resource);
        }
    }
    without that finally block then my resource (whatever that may be) may not be handed back.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    camel-man is offline Member
    Join Date
    Jan 2016
    Posts
    19
    Rep Power
    0

    Default Re: How does 'finally' block ensure tht code which could b bypassed by 'return' execu

    Java Code:
    class Test {
         
        public static void main (String [] args) {
            int i = alpha();
            
            System.out.println(i);
        }
     
            private static int alpha() {
            String [] stringArray = {"a", "b", "c"};
            
            try{
            for (String string : stringArray) {
                System.out.println("Printing... ");
            }
            System.out.println("blah ");
            return 4;
            } finally{
            System.out.println("After return.");//*************COMPILER NO LONGER COMPLAINS
            }
        }
    }
    Something like this proves that the finally statement is still being executed even though there is a return before it.

  4. #4
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Re: How does 'finally' block ensure tht code which could b bypassed by 'return' execu

    it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
    In other words, if we didn't have the finally block, the clean-up code could have been bypassed by a return, continue or break statement. But (in the case when we didn't have a finally block) a program containing a piece code, which can be bypassed by a return, continue, or break (i.e. it is unreachable because it occurs after a return, continue, or break), would simply Not compile (compiler errors I mentioned in question).

    So practically, in order for the program to compile, the clean up code would have to occur before the return, break, or continue. So finally block is not avoiding the bypassing of the code by return etc; it is rather the compiler/lint which is ensuring that the clean-up code does not get bypassed by return etc.

    Something like this proves that the finally statement is still being executed even though there is a return before it.
    Thank you. I understand that the finally block in your code is executed after the return, but what is confusing me is that does code ever get bypassed by a return, continue, or break?

  5. #5
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Re: How does 'finally' block ensure tht code which could b bypassed by 'return' execu

    without that finally block then my resource (whatever that may be) may not be handed back.
    Yeah, but there isn't a continue, break or return preventing that resource from being handed back. Am I missing something?

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: How does 'finally' block ensure tht code which could b bypassed by 'return' execu

    Quote Originally Posted by Zarah View Post
    but what is confusing me is that does code ever get bypassed by a return, continue, or break?
    I think you are missing the point (or I am). If the programmer forgot to handle the cleanup prior to returning (or an unexpected return happened), then that code is bypassed. Here is an example:

    Java Code:
    public class FinallyDemo {
    
       public static void main(String[] args) {
          System.out.println(perform(1));
          System.out.println(perform(3));
          System.out.println(perform(4));
          System.out.println(perform(8));
          System.out.println("Now for code with bypassed or forgotten cleanup.");
          System.out.println(perform2(1));
          System.out.println(perform2(3));
          System.out.println(perform2(4));
          System.out.println(perform2(8));
       }
    
       public static int perform(int a) {
          try {
             if (a == 1) {
                // clean up for a == 1
                return 10;
             } else if (a == 3) {
                // clean up for a == 3
                return 20;
             } else if (a == 4) {
                // clean up for a == 4
                return 30;
             }
             // cleanup for other a
             a = 99;
             return 40;
          }
          finally {
             cleanUp(a);
          }
       }
    
       public static int perform2(int a) {
          if (a == 1) {
             cleanUp(1);
             return 10;
          } else if (a == 3) {
             cleanUp(3);
             return 20;
          } else if (a == 4) {
             cleanUp(4);
             return 30;
          }
          // Uh oh! Forgot cleanup code.
          return 40; // accidentally bypassed.
       }
    
       public static void cleanUp(int value) {
          System.out.println("Cleaning up for value - value = " + value);
       }
    }
    Imagine a more complicated example where multiple returns, couple with continue and break statements are possible from a variety of locations within the code. It is possible that a return, continue, or break could happen, unexpectedly where the programmer forgot to handle the cleanup.

    Regards,
    Jim
    Last edited by jim829; 02-03-2016 at 11:36 PM.
    Zarah likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Static Block in java executes first
    By rdehankar in forum New To Java
    Replies: 2
    Last Post: 03-21-2014, 02:20 PM
  2. Replies: 2
    Last Post: 08-30-2012, 04:51 PM
  3. Code executes after thread
    By bubbless in forum New To Java
    Replies: 5
    Last Post: 11-27-2009, 05:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •