为什么 Scala 尝试不捕获 java.lang.StackOverflowError? [英] Why does Scala Try not catching java.lang.StackOverflowError?

查看:55
本文介绍了为什么 Scala 尝试不捕获 java.lang.StackOverflowError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些可以(可能)产生 StackOverflowError 的函数.当然,这是一个糟糕设计的迹象,但现在我决定将它包装到 Try 中.

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

我期望的结果是Failure(java.lang.StackOverflowError).我得到的结果只是 java.lang.StackOverflowError.我想问题是 StackOverflowError 不是异常,而是一个错误.如果是,是否有任何方法可以通过使用 Try 或其他一些 monad 来捕获"这些类型的错误?

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?

推荐答案

根据 Scala 文档.

According to Scala documentation.

注意:Try 上的组合器仅捕获非致命异常(见 scala.util.control.NonFatal).另一方面,严重的系统错误手,将被抛出.

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.

Throwable ->错误Try捕获.

我将实现一些包装器,允许为您的案例处理Errors:

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

这篇关于为什么 Scala 尝试不捕获 java.lang.StackOverflowError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆