0

I'm trying to get which line is generating an error when calling a kotlin script from java.

The following code gives line number -1.

try
{
    String scriptcode = "\n\nthrow Exception()";
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByExtension("kts");
    engine.eval(scriptcode);
}
catch(ScriptException se)
{
    System.out.println(se.getLineNumber());
}

Am I missing something?

nevcx
  • 520
  • 6
  • 9
  • Presumably the line number is [unavailable](https://docs.oracle.com/javase/10/docs/api/javax/script/ScriptException.html#getLineNumber()) because you're running the script from a string, not a file. – David Conrad May 12 '20 at 14:44
  • I take it back, I tried something similar with `js` instead of `kts` and got the expected line number. Apparently it's a limitation of Kotlin. – David Conrad May 12 '20 at 17:17
  • Reported as a bug. https://youtrack.jetbrains.com/issue/KT-38893 – nevcx Aug 27 '20 at 12:52

1 Answers1

0

Could please try something like this. se.getStackTrace()[0].getLineNumber();

UnknownBeast
  • 828
  • 1
  • 5
  • 13
  • That gives line 101. Probably from org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.asJsr223EvalResult(KotlinJsr223JvmScriptEngineBase.kt:101) which I get from se.printStackTrace(); – nevcx May 12 '20 at 09:41
  • yep I believe the same. – UnknownBeast May 12 '20 at 09:45