• Post Reply Bookmark Topic Watch Topic
  • New Topic

try try finally catch  RSS feed

 
pchandra iyer
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got this code I am not able to understand how it gets executed.


Any help would highly appreciated.
[edit]Tidy up indentation. CR[/edit]
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not able to understand how it gets executed.

What exactly don't you understand ? The execution flow ? The structure ?
 
pchandra iyer
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am confused with the execution

I think that the exception would bubble up the stack until it is handle.

In above code the catch would get executed and then the finally. Correct me if I am wrong.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
pchandra iyer wrote:In above code the catch would get executed and then the finally. Correct me if I am wrong.

Did you try it out? What did you see? Why do you think the catch would be executed first?
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You ought to have indented the code correctly; I have edited your indentation and I think that will help you see what is happening.
 
pchandra iyer
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot guys,
I was wrong, "finally" did got executed first. And then the catch.

Catch block executes no matter what.

If I would have removed the "catch" block from above code and if I would have added it to the calling function that would have got executed.

I think the conclusion is even if java doesn't mandate to have a catch block. For every exception there would be some catch block somewhere in the stack getting executed.

 
pchandra iyer
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell for indenting the code. That was a great help.
Thanks a lot once again
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome. It shows the value of indentation and the code tags.

Actually it is more accurate to say "finally" gets executed whatever. The "catch" is only executed if the appropriate Exception occurs; your "throw" statement ensures there is in fact always an Exception.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!