Java's try-catch-finally
does not catch a fatal error,
Scala's try-catch-finally
also catches fatal errors.
Well-known fatal exceptions include ʻOutOfMemoryError`, and such fatal exceptions should not be caught in the program.
scala> try {
| throw new StackOverflowError
| } catch {
| case e: Throwable => println("error")
| }
error
Therefore, in Scala, it is common (?) To catch exceptions using scala.util.Try
instead of try-catch-finally
.
scala.util.Try
, like Java's try-catch-finally
, only catches non-fatal errors (NonFatalError).
scala> Try(throw new StackOverflowError) recover {
| case e: Throwable => println("error")
| }
java.lang.StackOverflowError
at .$anonfun$res13$1(<console>:13)
at scala.util.Try$.apply(Try.scala:209)
... 38 elided
But scala.util.Try
becomes Failure
when an exception is thrown, and there is no mechanism like finally
to do something at the end. I want to finally
in Scala. I think there is such a time.
In such a case, there is a way to use scala.util.control.Exception.ultimately
. Finally
can be achieved by passing the last process to be executed regardless of whether an exception occurs.
scala> Try {
| ultimately {
| println("finally !")
| } {
| println("do something")
| throw new Exception
| println("no execute")
| }
| }
do something
finally !
res: scala.util.Try[Unit] = Failure(java.lang.Exception)
In this way, you can ignore fatal errors and only catch non-fatal errors.
Of course, if you don't need to use finally
, you don't need ʻultimately` either.
There are only two Japanese articles about scala.util.control.Exception.
As you commented, Scala's try-catch-finally
also
Pattern matching with NonFatal
in catch
can only catch non-fatal ones.
NonFatal Exception --scala_text
Recommended Posts