agi*_*eel 153

您可以将整个模式绑定到这样的变量:

try {
   throw new java.io.IOException("no such file")
} catch {
   // prints out "java.io.IOException: no such file"
   case e @ (_ : RuntimeException | _ : java.io.IOException) => println(e)
}
Run Code Online (Sandbox Code Playgroud)

请参阅Scala语言规范第118页第8.1.11段,称为模式替代方案.

观看模式匹配释放更深入的Scala中的模式匹配.


Did*_*ont 30

由于您可以在catch子句中访问scala的完整模式匹配功能,因此您可以做很多事情:

try {
  throw new IOException("no such file")
} catch {
  case _ : SQLException | _ : IOException => println("Resource failure")
  case e => println("Other failure");
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您需要一次又一次地编写相同的处理程序,则可以为此创建自己的控制结构:

def onFilesAndDb(code: => Unit) { 
  try { 
    code 
  } catch {
    your handling code 
  }
}
Run Code Online (Sandbox Code Playgroud)

对象scala.util.control.Exceptions中提供了一些此类方法.失败,failAsValue,处理可能正是你所需要的

编辑:与下面所说的相反,可以约束替代模式,因此提出的解决方案是不必要的复杂.请参阅@agilesteel解决方案

不幸的是,使用此解决方案,您无法访问使用替代模式的异常.据我所知,你不能用case绑定替代模式e @ (_ : SqlException | _ : IOException).因此,如果您需要访问异常,则必须嵌套匹配器:

try {
  throw new RuntimeException("be careful")
} catch  {
  case e : RuntimeException => e match {
    case _ : NullPointerException | _ : IllegalArgumentException => 
      println("Basic exception " + e)
    case a: IndexOutOfBoundsException => 
      println("Arrray access " + a)
    case _ => println("Less common exception " + e)
  }
  case _ => println("Not a runtime exception")
}
Run Code Online (Sandbox Code Playgroud)


Wil*_*ger 15

您还可以使用scala.util.control.Exception:

import scala.util.control.Exception._
import java.io.IOException

handling(classOf[RuntimeException], classOf[IOException]) by println apply { 
  throw new IOException("foo") 
}
Run Code Online (Sandbox Code Playgroud)

这个具体的例子可能不是说明如何使用它的最佳例子,但我发现它在很多场合都非常有用.