Scala: Silently catch all exceptions
Solution 1
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.)
Solution 2
In
import scala.util.Try
val res = Try (func()) toOption
if the Try is successful you will get a Some(value)
, if it fails a None
.
Solution 3
Try adding
case x =>
in your catch block :)
Solution 4
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
}
Solution 5
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 virtue of being self-documenting.
scala> val y = try { throw new NullPointerException ; () } catch quietly
y: Unit = ()
Edit: syntax changes include fewer braces for try-catch, catching with a function and function literals taken as partial functions:
scala> def f(t: Throwable) = ()
def f(t: Throwable): Unit
scala> try throw null catch f
^
warning: This catches all Throwables. If this is really intended, use `case _ : Throwable` to clear this warning.
scala> def f: PartialFunction[Throwable, Unit] = _ => ()
def f: PartialFunction[Throwable,Unit]
scala> try ??? catch f
tmporaries
Updated on October 29, 2021Comments
-
tmporaries over 2 years
Empty catch block seems to be invalid in Scala
try { func() } catch { } // error: illegal start of simple expression
How I can catch all exceptions without their processing?