在Scala中一次性捕获多个异常 [英] Catching multiple exceptions at once in Scala

查看:159
本文介绍了在Scala中一次性捕获多个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Scala中同时捕获多个异常?有没有比C#更好的方法:一次捕捉多个异常

How to catch multiple exceptions at once in Scala? Is there a better way than in C#: Catch multiple exceptions at once?

推荐答案

您可以将整个模式绑定到如下变量:

You can bind the whole pattern to a variable like this:

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段,称为模式替代方案。

See the Scala Language Specification page 118 paragraph 8.1.11 called Pattern alternatives.

这篇关于在Scala中一次性捕获多个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆