Finally block does not set values of variable in java

java

Solution

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`

Problem

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.

Original source

Related problems