【问题标题】:Re-execute TRY block after the exception is handled异常处理后重新执行TRY块
【发布时间】:2011-11-11 23:43:22
【问题描述】:

从这个答案开始:

Scala continuation and exception handling

我想知道是否有办法在异常处理后重新执行整个 try 块(或示例代码中的 ctry 块)。

我的意思是,如果 resume() 操作可以将执行移至 try 块的第一条语句,而不是简单地从引发异常的语句中恢复执行。

非常感谢!

【问题讨论】:

  • 我认为它被称为“循环”。
  • 好的,下一个问题。假设 try 块引发异常。在 catch 块中,我更改了 try 块中的代码(使用字节码或重新编译的源代码)。有没有办法重新执行新的 try 块?
  • @Niko - 我不明白你在 catch 块中更改代码是什么意思。您是否在应用程序中动态重新加载类定义,而程序位于该类中?你将如何做到这一点并不明显(或者这是否是你的意思),所以更多细节会非常有帮助。

标签: scala exception-handling continuations


【解决方案1】:

这是一个愚蠢的例子,我认为它会引导你找到答案:

object Retry

object SO_7331489 extends App {

  import scala.util.continuations._

  var dividend: String = "ten"
  var divisor: Int = 0

  val quotient = reset {

    shift { k: (Unit => Any) =>
      def retry: Any =
        k() match {
          case Retry => retry
          case x     => x
        }
      retry
    }

    try {
      dividend.toInt / divisor
    } catch {
      case e: java.lang.NumberFormatException =>
        println("caught " + e.getClass.getName + "(" + e.getMessage + ")")
        dividend = "10"
        println("retrying with dividend = \"10\"")
        Retry
      case e: java.lang.ArithmeticException =>
        println("caught " + e.getClass.getName + "(" + e.getMessage + ")")
        divisor = 2
        println("retrying with divisor = 2")
        Retry
      case t: Throwable =>
        println("caught " + t.getClass.getName + "(" + t.getMessage + ")")
        // Nothing left to retry, so don't return Retry
    }

  }

  println("quotient: " + quotient)

}

这个想法是在 try/catch 块之前触发 shift 块。在catch 块内,如果您想重试整个过程,只需返回Retry 对象即可。

将整个 shift 块提取到一个简单的函数中(例如 retry)可能会很好,但为了清楚起见,我将其保留为内联。

此代码产生以下输出:

[info] Running SO_7331489 
caught java.lang.NumberFormatException(For input string: "ten")
retrying with dividend = "10"
caught java.lang.ArithmeticException(/ by zero)
retrying with divisor = 2
quotient: 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2014-07-15
    • 2017-02-23
    相关资源
    最近更新 更多