如何在Scala REPL中找出抛出异常的行?

3

我有一段在Scala的REPL中运行的代码。 代码抛出了异常。 如何找出是哪一行出现了异常? 虽然堆栈跟踪中有行号,但它们是错误的。 在下面的示例中,堆栈跟踪显示异常在第13行抛出,但实际上该代码只有5行。

$ scala
Welcome to Scala 2.12.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_171).
Type in expressions for evaluation. Or try :help.

scala> :paste
// Entering paste mode (ctrl-D to finish)

if (math.random > 0.5) {
  throw new Exception()
} else {
  throw new Exception()
}

// Exiting paste mode, now interpreting.

java.lang.Exception
  ... 28 elided

scala> lastException.printStackTrace
java.lang.Exception
        at $line3.$read$$iw$$iw$.<init>(<console>:13)
        at $line3.$read$$iw$$iw$.<clinit>(<console>)
        at $line3.$eval$.$print$lzycompute(<console>:7)
        at $line3.$eval$.$print(<console>:6)
        at $line3.$eval.$print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:742)
1个回答

3

我在使用Ammonite REPL时,运气更好。

@ {
    if (math.random > 0.5) {
      throw new Exception()
    } else {
      println("here")
      throw new Exception()
    }
  }
java.lang.Exception
  ammonite.$sess.cmd2$.<init>(cmd2.sc:2)
  ammonite.$sess.cmd2$.<clinit>(cmd2.sc)


@

@ {
    if (math.random > 0.5) {
      throw new Exception()
    } else {
      println("here")
      throw new Exception()
    }
  }
here
java.lang.Exception
  ammonite.$sess.cmd3$.<init>(cmd3.sc:5)
  ammonite.$sess.cmd3$.<clinit>(cmd3.sc)

如果将if语句作为第1行,那么第2行和第5行似乎是异常可能被抛出的地方。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接