Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Throw Error vs Return Try?

Tags:

scala

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] = ???
like image 734
clay Avatar asked Aug 31 '14 15:08

clay


People also ask

How do you throw an error in Scala?

In scala, throwing an exception is the same as Java. we create an exception object and then we throw it with the throw keyword: Example: Scala.

What kind of error handling does Scala have?

Exception handling is the mechanism to respond to the occurrence of an exception. Exceptions can be checked or unchecked. Scala only allows unchecked exceptions, though. This means that, at compile-time, we won't be able to know if a method is throwing an exception we are not handling.

Is Scala try a Monad?

With unit = Try , Try is not a monad, because the left unit law fails.

What is try in Scala?

The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala. util. Either type. Instances of Try[T] , are either an instance of scala.


1 Answers

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
}
like image 52
Gabriele Petronella Avatar answered Oct 30 '22 10:10

Gabriele Petronella