1

实际上我在 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 }
}

但我仍然对第一种情况感到困惑。

4

1 回答 1

4

这似乎是因为您要返回整个try块的结果。如果你移动你return的块内部,没关系:

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

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

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

虽然这失败了:

def parse: Int = {
  for (x <- List(1))
    return try { 1 } catch { case _ => 0 }
  0
}
于 2012-01-17T04:15:06.073 回答