Reputation: 4624
I'm a beginner to scala programming and jvm languages. I want to convert a string in yyyy-MM-dd
to date format like this:
import java.text.SimpleDateFormat
import java.util.Date
val format = new SimpleDateFormat("yyyy-MM-dd")
def strTodate(stringDate: String): Date = {
format.parse(stringDate)
}
How can I can take care of exception in case strTodate
is called on a wrongly formatted string like strTodate("18/03/03") ? I'll like to handle the exception and also print the string
Upvotes: 0
Views: 374
Reputation: 31222
scala has three ways to handle errors.
Option
: has None
or Some
Try
: has Success
or Failure
Either
: has left or right. Right
is always right result.I prefer Either
of all and here is how you can do it as Either[String, Date]
where Left is String
, Right is Date
.
Example,
import java.text.SimpleDateFormat
import java.util.Date
import scala.util.Try
import scala.util.{Failure, Success}
val format = new SimpleDateFormat("yyyy-MM-dd")
def strTodate(stringDate: String): Either[String, Date] = {
Try {
format.parse(stringDate)
} match {
case Success(s) => Right(s)
case Failure(e: ParseException) => Left(s"bad format: $stringDate")
case Failure(e: Throwable) => Left(s"Unknown error formatting : $stringDate")
}
}
val date1 = strTodate("2018-09-26")
println(date1) // Right(Wed Sep 26 00:00:00 PDT 2018)
val date2 = strTodate("2018/09/26")
println(date2) // Left(bad format: 2018/09/26)
Upvotes: 2
Reputation: 4133
Handling exceptions:
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
object app {
val format = new SimpleDateFormat("yyyy-MM-dd")
def strTodate(stringDate: String): Either[Exception, Date] = {
try {
Right(format.parse(stringDate))
} catch {
case ioException : IOException =>
Left(ioException)
case e: Exception =>
Left(e)
}
}
def main(args: Array[String]) : Unit =
strTodate("2018-02-02") match {
case Right(date) => println(date)
case Left(err) => println(err.getMessage)
}
}
Upvotes: 0