Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

doubt about try catch finally and method return  RSS feed

 
raminaa niilian
Ranch Hand
Posts: 551
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
thank you for reading my post
I am just wondering why should the finally block execute even if i return from the method in try block ?



about the above code it always execute the finally block , i was thinking that return will return from he method where ever it is :-)
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the finally block terminates abruptly like with a return statement, then if there was a return statement executed in the try block or in one of the catch blocks, that statement is ignored, and the try-catch-finally ends for the reason the finally ended.
 
Sanjaya Sugiarto
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
finally is ALWAYS terminated, no matter where you place your return in try/catch block or even if exceptions occur.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well... not exactly always
 
Sanjaya Sugiarto
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Garrett Rowe:
Well... not exactly always


Clever response!!! My bad to say "always", must remember: for every rule there is at least one exception...thanks to point it out
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's actually interesting that the finally clause is guaranteed to run (assuming JVM doesn't exit). Instead of common code that looks like this...



You can do something like this...



Now... I am not going to say which is better though...
Henry
[ October 21, 2006: Message edited by: Henry Wong ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by raminaa niilian:
I am just wondering why should the finally block execute even if i return from the method in try block ?


Well, because that's exactly what it is meant to be used for: executing code that should *always* be executed when the try block ends. Common use is freeing resources that have been in use, such as streams, database connections etc. When you are done with them, you typically want to release them no matter what.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!