[英]Exception in scala/java
I'm a beginner to scala programming and jvm languages. 我是scala编程和jvm语言的初学者。 I want to convert a string in
yyyy-MM-dd
to date format like this: 我想将
yyyy-MM-dd
的字符串转换为这样的日期格式:
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") ? 如果在格式错误的字符串如strTodate(“ 18/03/03”)上调用
strTodate
,我该如何处理异常? I'll like to handle the exception and also print the string 我想处理异常并打印字符串
scala has three ways to handle errors. scala有三种处理错误的方法。
Option
: has None
or Some
Option
: None
或Some
Try
: has Success
or Failure
Try
: Success
或Failure
Either
: has left or right. Either
:有左或右。 Right
is always right result. Right
永远是正确的结果。 I prefer Either
of all and here is how you can do it as Either[String, Date]
where Left is String
, Right is Date
. 我更喜欢
Either
,这是您可以通过Either[String, Date]
做到的Either[String, Date]
其中Left是String
,Right是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)
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.