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?
It is best practice in Scala to handle exceptions using a try{...} catch{...} block, similar to how it is used in Java, except that the catch block uses pattern matching to identify and handle exceptions.
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.
With unit = Try , Try is not a monad, because the left unit law fails.
Throwable is just an alias for java. lang. Throwable . So in Scala, a catch clause that handles Throwable will catch all exceptions (and errors) thrown by the enclosed code, just like in Java.
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.)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With