【问题标题】:Scala - java.lang.VerifyError with simple functionScala - 具有简单功能的 java.lang.VerifyError
【发布时间】:2012-01-17 04:00:43
【问题描述】:

实际上,我在 html 解析器中使用我的代码。但是这里我重写它以供测试。

def parse: Int = {
  var texts = Array("a.b.c.d.1321,123.f")
  for (text <- texts) {
    var lines = text.split("\\.")
    return try { lines(4).replaceAll("[^0-9]", "").toInt } catch { case _ => 0 }
  }
  0
}

致电parse,我遇到了这个异常:

java.lang.VerifyError: (class: $anonfun$parse$1, method: apply signature: (Ljava/lang/String;)Lscala/runtime/Nothing$;) Inconsistent stack height 0 != 3
        at .parse(<console>:10)
        at .<init>(<console>:10)
        at .<clinit>(<console>)
        at .<init>(<console>:11)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
        at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
        at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
        at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
        at java.lang.Thread.run(Thread.java:722)

我的问题是为什么代码会引发该异常?

已编辑

请不要提及编码风格,只关注异常。因为代码可以编译成功。

已编辑

改变一点结果:

def parse: Int = {
  var texts = Array("a.b.c.d.1321,123.f")
  for (text <- texts) {
    var lines = text.split("\\.")
    return try { lines(4).replaceAll("[^0-9]", "").toInt } catch { case _ => -1 }
  }
  0
}

如果我不使用for循环,也可以:

def parse: Int = {
  var text = "a.b.c.d.1321,123.f"
  var lines = text.split("\\.")
  return try { lines(4).replaceAll("[^0-9]", "").toInt } catch { case _ => -1 }
}

但我仍然对第一个案例感到困惑。

【问题讨论】:

    标签: java function scala verifyerror


    【解决方案1】:

    这似乎是因为您要返回整个 try 块的结果。如果您将 return 移动到块内,就可以了:

    try { return lines(4).replaceAll("[^0-9]", "").toInt } catch { case _ => return 0 }
    

    这看起来像是一个与在 for 循环内返回 try 块相关的编译器错误。请注意,这可以正常工作:

    def parse: Int = {
      return try { 1 } catch { case _ => 0 }
      0
    }
    

    虽然失败:

    def parse: Int = {
      for (x <- List(1))
        return try { 1 } catch { case _ => 0 }
      0
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多