Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Silently catch all exceptions

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?

like image 958
tmporaries Avatar asked Jan 16 '14 18:01

tmporaries


People also ask

How do you catch exceptions in Scala?

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.

Can we have try finally without catch?

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.

Is Scala try a Monad?

With unit = Try , Try is not a monad, because the left unit law fails.

What is throwable Scala?

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.


2 Answers

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.)

like image 103
Rex Kerr Avatar answered Sep 21 '22 14:09

Rex Kerr


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.

like image 41
elm Avatar answered Sep 23 '22 14:09

elm