Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Output after finally

 
Thomas Hauck
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the following code

The output is
1,4,5.

Is the number "5" after finally printed
because the origin of the exception
is from within the
"main" method?

After the ArithmeticException is caught and the finally clause is executed,
why does it proceed to the last output statement in main?




 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thomas Hauck wrote:why does it proceed to the last output statement in main?

Because the finally only applies to the try/catch statement, not the whole method. So as soon as the finally block has been executed, the code just carries on to the next statement in the method.

Thomas Hauck wrote:After the ArithmeticException is caught and the finally clause is executed,

Of course, if you hadn't caught the ArithmeticException then the exception would have been thrown after the finally clause had executed and you wouldn't have seen the last print statement.
 
C Jay
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If ArithmeticException is not caught, the output will be 2,4,5 {will fall thru' RuntimeException (again a subclass of superclass Exception), finally and after finally}

If RuntimeException is also not caught, the output will be 3,4,5 {will fall thru' Exception (superclass), finally and after finally}

In the absence of all catch blocks, output will be 5 {finally} and then JVM ArithmeticException divide by zero.
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
C Jay wrote:If ArithmeticException is not caught, the output will be 2,4,5 {will fall thru' RuntimeException (again a subclass of superclass Exception), finally and after finally}

If RuntimeException is also not caught, the output will be 3,4,5 {will fall thru' Exception (superclass), finally and after finally}

In the absence of all catch blocks, output will be 5 {finally} and then JVM ArithmeticException divide by zero.

You're right. I didn't notice that the three exceptions were a hierarchy. Although the last one should be 4 (the value in the finally block), not 5.
 
C Jay
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry.. that was a typo. 4 in finally is correct.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic