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.
It seems to be because you're returning the result of the entire
tryblock. If you move yourreturninside the block, it's fine:It looks like a compiler bug related to returning the
tryblock inside aforloop. Notice that this works fine:while this fails: