clay clay - 1 month ago 7
Scala Question

Scala: Throw Error vs Return Try?

Should a Scala API ideally throw exceptions or return a Try value? Is there an official guideline regarding this?

def doSomethingMayThrow(): A = ???
def doSomethingWontThrow(): Try[A] = ???

Answer

Never throw exceptions for recoverable errors.

Returning appropriate data structure representing a possible failure (a Future, a Try, an Either and so on) is always preferable than throwing exceptions in the wild. It will inform the caller about the possibility of a failure, and it will force them to manage it.

Exceptions should only be thrown for unrecoverable errors, such as hardware failures and similar.

Let's make an example:

def throwOnOdds(x: Int): Int =
   if (x % 2 == 0) x / 2 else throw new Exception("foo")

val x = throwOnOdds(41) + 2 // compiles and explodes at runtime

now, let's make it better

def throwOnOdds(x: Int): Try[Int] =
   if (x % 2 == 0) Success(x / 2) else Failure(new Exception("foo"))

val x = throwOnOdds(41) + 2 // doesn't compile

Not handling the failure leads to a compile-time error, which is way better than a runtime one. Here's how to handle it

throwOnOdds(41) match {
  case Success(n) => // do something with n
  case Failure(e) => // handle exception
}