scala 如何忽略异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3960327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:30:58  来源:igfitidea点击:

How do I ignore an exception?

scala

提问by Basilevs

Is there more elegant way to write the following?

有没有更优雅的方式来写以下内容?

try {
    ... // Some throwing code
    return first
} 
catch {
    case e:ExceptionType => {} // No code to execute. Ignore error.
}
return second

回答by Daniel C. Sobral

scala.util.control.Exception.ignoring(classOf[ExceptionType]) {
  ... // Some throwing code
}

回答by Rex Kerr

@Daniel has already provided the canonical method to use to do this. Look through the other methods in scala.util.control.Exception--they are quite helpful and generic!

@Daniel 已经提供了用于执行此操作的规范方法。查看 -- 中的其他方法,scala.util.control.Exception它们非常有用且通用!

If you need to get a return value out of the try block, use failinginstead of ignoring(but be aware that the result is an Any, i.e. not typesafe).

如果您需要从 try 块中获取返回值,请使用failing而不是ignoring(但要注意结果是Any,即不是类型安全的)。

You can also write your own exception-catcher, which will be a little slow for heavy-duty work but otherwise nice to use:

您还可以编写自己的异常捕获器,这对于繁重的工作会有点慢,但使用起来很不错:

class DefaultOn[E <: Exception] {
  def apply[A](default: => A)(f: => A)(implicit m: Manifest[E]) = {
    try { f } catch { case x if (m.erasure.isInstance(x)) => default }
  }
}
object DefaultOn { def apply[E <: Exception] = new DefaultOn[E] }

scala> DefaultOn[NumberFormatException](0) { "Hi".toInt }
res0: Int = 0

Or if you like options:

或者,如果您喜欢选项:

class TryOption[E <: Exception] {
  def apply[A](f: => A)(implicit m: Manifest[E]) = {
    try { Some(f) } catch { case x if (m.erasure.isInstance(x)) => None }
  }
}
object TryOption { def apply[E <: Exception] = new TryOption[E] }

scala> TryOption[NumberFormatException] { "Hi".toInt }
res1: Option[Int] = None

Or you can be inspired by this plus the library routines and create your own methods to ignore multiple different exceptions and preserve types on the return value.

或者您可以受到此以及库例程的启发,并创建自己的方法来忽略多个不同的异常并保留返回值的类型。

回答by Vasil Remeniuk

In Scala all exceptions are not checked, so if you don't want, you may just skip handling them (and thus exception will be escalated to a higher level). Silently ignoring an exception the way you want to do is generally a bad practice. However, your code can be shortened to:

在 Scala 中,不会检查所有异常,因此如果您不想要,您可以跳过处理它们(因此异常将升级到更高级别)。以您想要的方式默默地忽略异常通常是一种不好的做法。但是,您的代码可以缩短为:

try {
  ... // Some throwing code
} catch {
  case e:ExceptionType => 
}

回答by jonathanChap

Hows about:

怎么样:

Try { 
     // some throwing code 
}

This will ignore all non fatal exceptions, which is what you want to do most of the time.

这将忽略所有非致命异常,这是您大部分时间想要做的。