小编use*_*511的帖子

Scala:如何捕获子线程中的异常

我原以为Try捕获跨线程异常,如下例所示。我想不是:那么如何捕获生成的子线程中的异常呢?

// Simple class that throws error
class Child extends Runnable {
  def run {
    val exception: Exception = new Exception("Foo")
    val i = 1
    Thread.sleep(1000)
    val lines = scala.io.Source.fromFile("/tmp/filefoobar.txt").mkString
    Thread.sleep(1000)
  }
}
// spawn the class above
def Parent() = {
  val doit = Try {
    val t = new Thread(new Child)
    t.start
    t.join()
  }

  doit match {
    case Success(v) => println("uh oh did not capture error")
    case Failure(v) => println("good we caught the error")
  }
} …
Run Code Online (Sandbox Code Playgroud)

scala exception

5
推荐指数
1
解决办法
1652
查看次数

标签 统计

exception ×1

scala ×1