Scala: Silently catch all exceptions

后端 未结 8 1587
佛祖请我去吃肉
佛祖请我去吃肉 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 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.)

提交回复
热议问题