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] = ???
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.
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.
With unit = Try , Try is not a monad, because the left unit law fails.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With