Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Getting try/catch to work in Scala
import java.time.LocalDate
import java.time.TemporalAdjusters
import scala.util.{Success, Failure, Try}
import org.scalatest.FunSpec
/**
* Check if date passed is the last day of the month.
*/
object Check {
def endDateCheck(d: LocalDate): Try[String] = {
val lastDay = d.`with`(d.getMonth).`with`(TemporalAdjusters.lastDayOfMonth)
val error: String = "Warning! Date passed is not last day of month."
if (d == lastDay) Success("")
else Failure(new Exception(error))
}
}
object Main {
def evaluate(d: LocalDate): Try[String] = {
Try(Check.endDateCheck(d)) match {
case Failure(fail) => Failure(fail)
case Success(_) => Success("")
}
}
}
class CheckSpec exends FunSpec {
describe("Try/Catch example") {
it("should return a value") {
Main.evaluate(LocalDate.of(2017, 10, 31)) match {
case Failure(error) => println(error)
case Success(result) => assert(result.isEmpty)
}
}
it ("should return an error") {
Main.evaluate(LocalDate.of(2017, 10, 1)) match {
case Failure(error) => assert(error.getMessage == "Warning! Date passed is not last day of month.")
case Success(result) => println(result)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.