我原以为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)