在 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以将整个模式绑定到一个变量,如下所示:
请参阅 Scala 语言规范第 118 页第 8.1.11 段 称为模式替代方案。
观看模式匹配释放,深入了解 Scala 中的模式匹配。
You can bind the whole pattern to a variable like this:
See the Scala Language Specification page 118 paragraph 8.1.11 called Pattern alternatives.
Watch Pattern Matching Unleashed for a deeper dive into pattern matching in Scala.
由于您可以在 catch 子句中访问 scala 的完整模式匹配功能,因此您可以做很多事情:
请注意,如果您需要一次又一次编写相同的处理程序,您可以为此创建自己的控制结构:
一些这样的方法在对象 scala.util.control.Exceptions< 中可用/a>. failed、failAsValue、处理可能正是您所需要的
编辑:与下面所述相反,可以绑定替代模式,因此建议的解决方案不必要地复杂。请参阅@agilesteel 解决方案
不幸的是,使用此解决方案,您无法访问使用替代模式的异常。据我所知,您无法使用 case
e @ (_ : SqlException | _ : IOException)
绑定替代模式。因此,如果您需要访问异常,则必须嵌套匹配器:As you have access to the full pattern matching capabilities of scala in the catch clause, you can do a lot :
Note that if you need to write the same handlers time and time again you can create your own control structure for that :
Some such methods are available in object scala.util.control.Exceptions. failing, failAsValue, handling may be just what you need
Edit : Contrary to what is said below, alternative patterns can be bound, so the proposed solution is needlessly complex. See @agilesteel solution
Unfortunately, with this solution, you have no access to the exception where you use the alternative patterns. To my knowledge, you cannot bind on an alternative pattern with case
e @ (_ : SqlException | _ : IOException)
. So if you need access to the exception, you have to nest matchers :您还可以使用 scala.util.control.Exception:
这个具体示例可能不是说明如何使用它的最佳示例,但我发现它在很多情况下非常有用。
You can also use
scala.util.control.Exception
:This specific example might not be the best example to illustrate how you can use it, but I find it pretty useful in many occasions.
Scala 版本 3(2021 年发布)支持 union types,它为已经提到的解决方案创建了另一个解决方案,虽然它看起来非常非常相似,但它有所不同:(
为了比较,我使用了解决方案 https://stackoverflow.com/a/6385333/1039774 从 2011 年起,将其更改为具有联合类型的 Scala 3,并且在 Scala 3 中可以省略
new
运算符。)Scala version 3 (released in 2021) supports union types, which creates another solution to the already mentioned solutions, although it looks very very similar, but it's different:
(For comparison, I've used the code from solution https://stackoverflow.com/a/6385333/1039774 from 2011, and changed it to Scala 3 with union types, and the
new
operator can be omitted in Scala 3.)这对我来说是唯一的方法,它通过了 sbt clean 覆盖率测试coverageReport,而没有抛出令人讨厌的解析异常......
This was the only way for me, which passed trough the
sbt clean coverage test coverageReport
without throwing the nasty parsing exception ...