Skip to content

Instantly share code, notes, and snippets.

@Kalimaha
Created August 11, 2016 23:31
Show Gist options
  • Select an option

  • Save Kalimaha/163eae8cfe769d0c43097d7c6753f69b to your computer and use it in GitHub Desktop.

Select an option

Save Kalimaha/163eae8cfe769d0c43097d7c6753f69b to your computer and use it in GitHub Desktop.
Exceptions Handling with Scala
package com.rea.core
import scala.util.Try
object MathUtils {
def divide(x: Integer, y: Integer): Option[Double] = {
if (y == 0) None
else Some(x / y)
}
def divide2(x: Integer, y: Integer): Either[String, Double] = {
if (y == 0) Left("Can't divide by zero.")
else Right(x / y)
}
def divide3(x: Integer, y: Integer): Either[String, Double] = {
try {
Right(x / y)
} catch {
case e: ArithmeticException => Left(e.getMessage)
case e: Exception => Left("Something else happend.")
}
}
def divide4(x: Integer, y: Integer): Try[Double] = {
Try(x / y)
}
}
package com.rea
import com.rea.core.MathUtils
import org.scalatest.FunSuite
import scala.util.{Failure, Success}
class TestMathUtils extends FunSuite {
test("y is not zero") {
assert(MathUtils.divide(4, 2).get == 2.0)
}
test("y is zero") {
assert(MathUtils.divide(4, 0).isEmpty)
}
test("y is not zero (with Either)") {
assert(MathUtils.divide2(4, 2).right.get == 2.0)
}
test("y is zero (with Either)") {
assert(MathUtils.divide2(4, 0).left.get == "Can't divide by zero.")
}
test("y is zero (with Either and Exception)") {
assert(MathUtils.divide3(4, 0).left.get == "/ by zero")
}
test("y is NOT zero (with Try)") {
MathUtils.divide4(4, 2) match {
case Success(t) => succeed
case Failure(t) => fail()
}
}
test("y is zero (with Try)") {
MathUtils.divide4(4, 0) match {
case Success(t) => fail()
case Failure(t) => succeed
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment