Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

scala

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?

like image 836
ig-melnyk Avatar asked Jun 27 '16 11:06

ig-melnyk


People also ask

Can you catch StackOverflowError Java?

StackOverflowError is an error which Java doesn't allow to catch, for instance, stack running out of space, as it's one of the most common runtime errors one can encounter.

What causes a Java Lang StackOverflowError?

StackOverflowError is a runtime error which points to serious problems that cannot be caught by an application. The java. lang. StackOverflowError indicates that the application stack is exhausted and is usually caused by deep or infinite recursion.

Why am I getting a stack overflow error?

The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.


1 Answers

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(..)
}
like image 90
vvg Avatar answered Sep 19 '22 06:09

vvg