将多个异常类型匹配到同一案例

发布于 2024-12-20 18:54:50 字数 312 浏览 1 评论 0原文

当将异常与 case 语句进行模式匹配时,是否有更简化的方法将相同的异常与一组异常类型匹配?而不是这样:

} catch {
  case e if e.isInstanceOf[MappingException] || e.isInstanceOf[ParseException] => 

这样的事情会很好:

case e: MappingException | ParseException | SomeOtherException =>

这样的事情可能吗?

When pattern matching an exception with a case statement, is there a more simplified way of matching the same exception to a set of exception types? Instead of this:

} catch {
  case e if e.isInstanceOf[MappingException] || e.isInstanceOf[ParseException] => 

Something like this would be nice:

case e: MappingException | ParseException | SomeOtherException =>

Is something like this possible?

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

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

舞袖。长 2024-12-27 18:54:50

您可以这样做:

catch {
  case e @ (_: MappingException | _: ParseException | _: SomeOtherException) =>
}

如果您尝试保存一些代码行并且定期处理相同类型的异常,您可以考虑预先定义一个部分函数来用作处理程序:

val myHandler: PartialFunction[Throwable, Unit] = {
  case e @ (_: MappingException | _: ParseException | _: SomeOtherException) =>
}

try {
  throw new MappingException("argh!")
} catch myHandler

You can do this:

catch {
  case e @ (_: MappingException | _: ParseException | _: SomeOtherException) =>
}

If you're trying to save some lines of code and you handle the same types of exceptions regularly, you might consider defining a partial function beforehand to use as a handler:

val myHandler: PartialFunction[Throwable, Unit] = {
  case e @ (_: MappingException | _: ParseException | _: SomeOtherException) =>
}

try {
  throw new MappingException("argh!")
} catch myHandler
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文