ig-melnyk ig-melnyk - 5 months ago 32
Java Question

Why does Scala Try not catching java.lang.StackOverflowError?

I have some function that can (possibly) produce StackOverflowError. Of course this is a sign of a bad design, but for now I decided to wrap it into the Try.

Try{
Calculator.eval(..)
}


The result I expect is Failure(java.lang.StackOverflowError).
The result I get is just java.lang.StackOverflowError. I suppose the problem is that StackOverflowError is not Exception, but an error. If it is, are there any ways to "catch" those kind of errors by using Try or some other monad?

Answer

According to Scala documentation.

Note: only non-fatal exceptions are caught by the combinators on Try (see scala.util.control.NonFatal). Serious system errors, on the other hand, will be thrown.

No Throwable -> Errors are catched by Try.

I would implement some wrapper that allow to handle Errors for your case:

object TryAll {
  def apply[K](f: => K): Try[K] =
    try { 
       Success(f)
    } catch {
      case e: Throwable => Failure(e)
    }
}


TryAll {
  Calculator.eval(..)
}