Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finally block does not set values of variable in java

Tags:

java

I have the below code.

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try{
            System.out.println("Hardik::"+testFinnalyBlock());  
        }catch(Exception e){
            System.out.println("hhh");
        }
    }


    public static int testFinnalyBlock() throws Exception{
        int a=5,b=10;
        int sum=0;
        try{
            sum = a+b;
            System.out.println("sum==="+sum);
            return sum;
        }catch(Exception e){
            System.out.println("In Catch");
        }finally{
            sum = a+30;
            System.out.println("sum==="+sum);
//          return 1;
        }
        return 1;
    }

The output of above code it Hardik::15, While i think it should be Hardik::35.

Can Anyone tell me how it works. Thanks.

like image 309
Hardik Patel Avatar asked Jul 21 '26 07:07

Hardik Patel


2 Answers

The finally block is being executed, based on your output...

sum===15
sum===35
Hardik::15

The problem is, the return statement in the try-catch section. finally won't update the value begin returned to the caller, because that value has already being placed in another part of memory...

Update

I'm a pretty old school, so I believe in one entry point and one exit point for all my methods...

Something like the following would produce the result you're trying to get...

public static int testFinnalyBlock() throws Exception {
    int a = 5, b = 10;
    int sum = 0;
    try {
        sum = a + b;
        System.out.println("sum===" + sum);
    } catch (Exception e) {
        System.out.println("In Catch");
    } finally {
        sum = a + 30;
        System.out.println("sum===" + sum);
    }
    return sum;
}

If you need to return a different value because of the error, you should be modifying sum in the catch section of your try-catch

like image 129
MadProgrammer Avatar answered Jul 23 '26 21:07

MadProgrammer


Remove return form try block and add at the end of the method. Try this code

   public static int testFinnalyBlock() throws Exception{
    int a=5,b=10;
    int sum=0;
    try{
        sum = a+b;
        System.out.println("sum==="+sum);

    }catch(Exception e){
        System.out.println("In Catch");
    }finally{
        sum = a+30;
        System.out.println("sum==="+sum);
    //          return 1;
    }
    return sum;
}

use finally block for clean up activity,not for logic.It is not good practice.

like image 31
Prabhaker A Avatar answered Jul 23 '26 21:07

Prabhaker A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!