Scala尝试和不同的失败案例

时间:2016-09-10 13:39:57

标签: scala

此代码返回"我已经失败"除外。

  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") } 具有不同的大小写?

我知道我可以这样做:

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")
}

这是实现这一目标的最佳方式,也是最简单的方法吗?

[编辑]

感谢Ashesh。对我来说,最不详的是:

@media (max-width: 768px){
  #menu-item-98 {
    display:none;
  }
}

2 个答案:

答案 0 :(得分:7)

您可以匹配Failure(e: ExceptionType)任何异常类型(是否为case类),无需创建自己的异常类型或两个模式匹配表达式:

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"

答案 1 :(得分:1)

没有。您可以匹配case class例外;

case class ExceptionOne(msg: String) extends Exception(msg)等等;

然后;

Try { /* ...*/ } match {
  case Failure(ExceptionOne(msg)) => println("exception of type 1")
  // more cases
  case Failure(e) => println("generic exception")
  case Success(s) => ???
}

或者,您可以匹配单个Failure并对其中包含的异常进行匹配,因此;

Try { /* ...*/ } match {
  case Failure(e) => e match {
    case e1: DifferentException => // do something with DifferentException
    case e: Exception => // do something with a generic exception
  }
  case Success(s) => ???
}