ScalaKnol: Why returning a value in finally is a bad idea


For those of us who are coming from an imperative background, we are used to using try catch rather losely. Ok, I am not trying to generalize here but a majority of us do so. When we come to the Scala world, we realise that like other expressions in scala, try-catch-finally would result in a value.

The general practice recommended is that finally should be used when we want something to be executed irrespective of whether it resulted in a value or ended up in a catch condition. A much used scenario is to clean up any resources in finally such as file.close()

Now, in scala since it would yield a value, the recommendation is that you should not change the value which was computed as a part of try or catch in the finally block. What happens if you do it?

To answer look at the following code blocks

  def f:Int = try {return 1} finally {return 2}   //> f: => Int
  println(f)                                      //> 2
                                                  
  def g:Int = try 1 finally 2                     //> g: => Int
  println(g)                                      //> 1

Since the code is done in Scala worksheet, you would be able to see the corresponding output as well.

The difference in the output is because Scala tries to keep the result compatible with what we see in Java, which is, if there is an explicit exception or a return specified in finally then the same would override the value computed in the try or catch block. Surprising ! That is the reason it is best avoided to change the values in finally and keep it for ensuring just side effects like releasing resources.

About Vikas Hazrati

Vikas is the CTO @ Knoldus which is a group of software industry veterans who have joined hands to add value to the art of software development. We do niche product and project development on Scala and Java. We consult and coach on effective software development and agile practices. With our focus on software craftsmanship you can be assured of a good quality at the right price. To know more, send a mail to info@knoldus.com or visit www.knoldus.com
This entry was posted in Scala and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s