Creating a Try

The definition of Try is already familiar because of its similarity to Either, and so are the ways of creating an instance of it. For starters, we can use the constructors of the case classes to create instances directly:

scala> import scala.util._
import scala.util._
scala> Success("Well")
res1: scala.util.Success[String] = Success(Well)
scala> Failure(new Exception("Not so well"))
res2: scala.util.Failure[Nothing] = Failure(java.lang.Exception: Not so well)

The idea behind Try is that it can be used in scenarios where an exception would normally be thrown. Hence, the constructors we just mentioned would normally form the following pattern:

try Success(System.console().readLine()) catch {
case err: IOError => Failure(err)
}

This will end with the result of the try block being wrapped in Success and the catch exception wrapped in Failure. Again, stdlib already has this pattern implemented in the companion object of Try. The apply method takes a single by-name parameter for the try block, like so:

Try(System.console().readLine())

And then catches all NonFatal exceptions.

NonFatal represents a class of exceptions that the developer is able to deal with. It does not include fatal errors such as OutOfMemoryError, StackOverflowError, LinkageError, or InterruptedException. It does not make sense to deal with these programmatically. Another group of Throwables not matched by NonFatal is scala.util.control.ControlThrowable, which is used internally to control program flow and thus should not be used in a catch exception either.

It is common to provide multiline blocks wrapped in curly braces as a parameter for the Try constructor to makes it appear like it's a language feature:

scala>val line = Try {
val line = System.console().readLine()
println(s"Got $line from console")
line
}

This constructor is so common that it covers the absolute majority of use cases.

Now, let's take a look at how we can get back the value from an instance of Try.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.126.199