exception – Issue with try-finally in Scala

exception – Issue with try-finally in Scala

For scala 2.13:
you can just use Using to acquire some resource and release it automatically without error handling if its an AutoClosable:

import java.io.FileReader
import scala.util.Using

val newStyle: Try[String] = Using(new FileReader(myfile.txt)) { 
  reader: FileReader =>
    // do something with reader
    something
}
newStyle
// will be 
// Failure(java.io.FileNotFoundException: myfile.txt (No such file or directory))
// if file is not found or Success with some value it will not fall

scala 2.12:

You can wrap your reader creation by scala.util.Try and if it will fall on creation you will get Failure with FileNotFoundException inside.

import java.io.FileReader
import scala.util.Try

val oldStyle: Try[String] = Try{
  val file = new FileReader(myfile.txt)
  try {
    // do operations on file
    something
  } finally {
    file.close() // close the file
  }
}
oldStyle
// will be 
// Failure(java.io.FileNotFoundException: myfile.txt (No such file or directory))
// or Success with your result of file reading inside

I recommend not to use try ... catch blocks in scala code. Its not type safety for some cases and can lead to non-obvious results but for release some resource in old scala versions there is the only way to do it – using tryfinally.

exception – Issue with try-finally in Scala

Leave a Reply

Your email address will not be published.