首页 > 解决方案 > 如何找出哪一行在scala repl中引发了异常?

问题描述

我有一段在 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)

标签: scala

解决方案


我对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 行在这里似乎是正确的,因为这里可以引发异常。


推荐阅读