ig-melnyk
ig-melnyk

Reputation: 2879

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?

Upvotes: 9

Views: 1203

Answers (1)

vvg
vvg

Reputation: 6385

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

Upvotes: 12

Related Questions