Searching online for the answer gives two prominent posts (Codacy's and Daniel Westheide's), and both give the same answer as Scala's official documentation for Try:
An important property of Try shown in the above example is its ability to pipeline, or chain, operations, catching exceptions along the way.
The example referenced above is:
import scala.io.StdIn
import scala.util.{Try, Success, Failure}
def divide: Try[Int] = {
val dividend = Try(StdIn.readLine("Enter an Int that you'd like to divide:\n").toInt)
val divisor = Try(StdIn.readLine("Enter an Int that you'd like to divide by:\n").toInt)
val problem = dividend.flatMap(x => divisor.map(y => x/y))
problem match {
case Success(v) =>
println("Result of " + dividend.get + "/"+ divisor.get +" is: " + v)
Success(v)
case Failure(e) =>
println("You must've divided by zero or entered something that's not an Int. Try again!")
println("Info from the exception: " + e.getMessage)
divide
}
}
But I can just as easily pipeline operations using the conventional try
block:
def divideConventional: Int = try {
val dividend = StdIn.readLine("Enter an Int that you'd like to divide:\n").toInt
val divisor = StdIn.readLine("Enter an Int that you'd like to divide by:\n").toInt
val problem = dividend / divisor
println("Result of " + dividend + "/"+ divisor +" is: " + problem)
problem
} catch {
case (e: Throwable) =>
println("You must've divided by zero or entered something that's not an Int. Try again!")
println("Info from the exception: " + e.getMessage)
divideConventional
}
(Note: divide
and divideConventional
differ slightly in behavior in that the latter errors out at the first sign of trouble, but that's about it. Try entering "10a" as input to dividend
to see what I mean.)
I'm trying to see scala.util.Try
's pipelining advantage, but to me it seems the two methods are equal. What am I missing?
Try(...)
only catches non-fatal exceptions, so it's equivalent to `try { ... } catch { case NonFatal(e) => ... } – HemolysisTry
is part of the type system. Any code that handles a value of typeTry
"knows" that it might be one or the other. A routine that might throw can wrap it in aTry
and pass it off as someone else's problem. Without theTry
there's no easy way to communicate, "Hey! Someone else needs to handle this." – Drama