Empty catch block seems to be invalid in Scala
try {
func()
} catch {
} // error: illegal start of simple expression
How I can catch all
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.
What about:
import scala.util.control.Exception.catching
catching(classOf[Any]) opt {func()}
It generates an Option like in some of the previous answers.
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
}
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
}
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 = ()
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.)