1

Consider the following code:

 int dummy() {     
     int x = 0; 
     try { 
        x = x + 1; 
        throw new Exception(); 
     } catch (Exception e) { 
       x = x + 2; 
       return x; 
     } finally {
      x = x + 4;  
 }

I need to "predict" the behaviour of this method without programming it. My question is, what will the return value be?

My guess would be that when an exception occurs, the finally block will be realized, so the value of x will be 4. But I think the value will not be returned. And if no exception occurs, the value will be 2 and it will be returned.

I'm a complete beginner (less than 3 months) in programming so I might be missing something.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
cody1
  • 95
  • 7

2 Answers2

1

The following things will happen when you will call this method:

  1. The expression, x = x + 1; will increase the value of x by 1 i.e. its value will become 1. Then, throw new Exception(); will be executed and as a result, the control will enter the catch block.
  2. Inside the catch block, x = x + 2; will increase the value of x by 2 i.e. its value will become 3 which is the value that will be returned.
  3. Since finally block is supposed to be executed irrespective of whether an exception is thrown or not, this block will be executed but it won't change the return value. Thus, finally block is useless here. Typically, finally block is used to release resources. Check this to learn more about it.
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

First, your int x is declared at 0.

You enter the try block and x becomes 1.

An Exception is thrown, hence the control moves to the catch block.

Here, x gets 2 more and goes to 3, then the value 3 is ready to be returned.

However, the execution continues to execute the finally block and x = x + 4 -> 7 but this doesn't change your return value since when you return an int you're passing its value, not the reference of the variable x.

If you want to know more, I'm sure who assigned you this puzzle will be glad to help!

Balastrong
  • 4,336
  • 2
  • 12
  • 31