Scala: Silently catch all exceptions

后端 未结 8 1521
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 05:34

Empty catch block seems to be invalid in Scala

try {
  func()
} catch {

} // error: illegal start of simple expression

How I can catch all

相关标签:
8条回答
  • 2020-12-31 05:56

    Just for a sake of completeness, there is a set of built-in methods in Exception, including silently catching exceptions. See Using scala.util.control.Exception for details on usage.

    0 讨论(0)
  • 2020-12-31 05:57

    What about:

    import scala.util.control.Exception.catching
    catching(classOf[Any]) opt {func()}
    

    It generates an Option like in some of the previous answers.

    0 讨论(0)
  • 2020-12-31 05:58

    Inside of Scala's catch block you need to use similar construct as in a match statement:

    try {
      func()
    } catch {
      case _: Throwable => // Catching all exceptions and not doing anything with them
    }
    
    0 讨论(0)
  • 2020-12-31 06:01

    I like one of the suggestions here to use Try() with toOption, but in case you don't want to go further with Option, you can just do:

    Try(func()) match {
      case Success(answer) => continue(answer)
      case Failure(e) => //do nothing
    }
    
    0 讨论(0)
  • 2020-12-31 06:10

    If annotating with Throwable is burdensome, you can also

    scala> def quietly[A]: PartialFunction[Throwable, A] = { case _ => null.asInstanceOf[A] }
    quietly: [A]=> PartialFunction[Throwable,A]
    
    scala> val x: String = try { ??? } catch quietly
    x: String = null
    

    which has the small virtual of being self-documenting.

    scala> val y = try { throw new NullPointerException ; () } catch quietly
    y: Unit = ()
    
    0 讨论(0)
  • 2020-12-31 06:14

    Some exceptions really aren't meant to be caught. You can request it anyway:

    try { f(x) }
    catch { case _: Throwable => }
    

    but that's maybe not so safe.

    All the safe exceptions are matched by scala.util.control.NonFatal, so you can:

    import scala.util.control.NonFatal
    try { f(x) }
    catch { case NonFatal(t) => }
    

    for a slightly less risky but still very useful catch.

    Or scala.util.Try can do it for you:

    Try { f(x) }
    

    and you can pattern match on the result if you want to know what happened. (Try doesn't work so well when you want a finally block, however.)

    0 讨论(0)
提交回复
热议问题