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?
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.
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.
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.
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(..)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With