Question

Actually I use my code in a html parser. But here I rewrite it for test.

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
}

Call parse, I got this exception:

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)

My question is why does the code raise that exception?

Edited

Please don't mention about the coding style, just focus on the exception. Because the code can be compiled successfully.

Edited

Change a little of result:

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
}

If I don't use for loop, it is ok:

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 }
}

But I'm still confused about the first case.

Was it helpful?

Solution

It seems to be because you're returning the result of the entire try block. If you move your return inside the block, it's fine:

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

It looks like a compiler bug related to returning the try block inside a for loop. Notice that this works fine:

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

while this fails:

def parse: Int = {
  for (x <- List(1))
    return try { 1 } catch { case _ => 0 }
  0
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top