在Scala中一次捕获多个exception

如何在Scala中一次捕获多个exception? 有没有比在C#中更好的方法: 一次捕获多个exception?

你可以将整个模式绑定到一个像这样的variables:

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

请参阅Scala语言规范第118页上的第8.1.11段,称为模式替代。

由于您可以在catch子句中使用scala的全部模式匹配function,所以您可以做很多事情:

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

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

 def onFilesAndDb(code: => Unit) { try { code } catch { your handling code } } 

对象scala.util.control.Exceptions中有一些这样的方法。 失败,failAsValue,处理可能正是你所需要的

编辑:与以下所述相反,可以限制替代模式,因此所提出的解决scheme是不必要的复杂的。 请参阅@agilesteel解决scheme

不幸的是,有了这个解决scheme,在使用替代模式的情况下,您将无法访问exception。 据我所知,你不能绑定在案件e @ (_ : SqlException | _ : IOException)的替代模式。 所以如果你需要访问exception,你必须嵌套匹配器:

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

你也可以使用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") } 

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