此代码作为异常(exception)返回“我失败了”。
Try({
throw new Exception()
}) match {
case Failure(e) => println("I've failed")
case Success(s) => println("I've succeeded")
}
但是如果我有不同的异常怎么办,例如:
Try({
if(someBoolean) {
throw new DifferentException()
} else {
throw new Exception()
}
}) match {
case Failure(e) => println("I've failed")
case Success(s) => println("I've succeeded")
}
如何更改匹配语句,以便我们对 Exception
和 DifferentException
有不同的情况?
我知道我可以做到:
Try({
if(true) {
throw new DifferentException()
} else {
throw new Exception()
}
}) match {
case Failure(e) if e.isInstanceOf[DifferentException] => println("I've failed differently")
case Failure(e) if e.isInstanceOf[Exception] => println("I've failed")
case Success(s) => println("I've succeeded")
}
这是最好的,即最不冗长的方式吗?
[编辑]
感谢 Ashesh。对我来说,最不冗长的是:
case class DifferentException() extends Exception() {}
Try({
if(someBoolean) {
throw new DifferentException
} else {
throw new Exception
}
}) match {
case Failure(DifferentException()) => println("I've failed differently")
case Failure(e) => println("I've failed")
case Success(s) => println("I've succeeded")
}
最佳答案
您可以为任何异常类型(无论是否为案例类)匹配Failure(e: ExceptionType)
,无需创建您自己的异常类型或两个模式匹配表达式:
def printResult(action: => Unit) = {
Try(action) match {
case Failure(e: IllegalArgumentException) => println("illegal arg exception")
case Failure(e) => println("other exception")
case _ => println("success")
}
}
printResult(throw new IllegalArgumentException) // prints "illegal arg exception"
printResult(throw new RuntimeException) // prints "other exception"
printResult(1) // prints "success"
关于Scala Try 和不同的失败案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39426645/