我曾經認爲Try
捕獲了跨線程異常,如下例所示。我猜不是的:那麼如何在生成的子線程中捕獲異常呢?Scala:如何捕獲子線程中的異常
// 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")
}
}
輸出 階>父()
Exception in thread "Thread-35" java.io.FileNotFoundException: /tmp/filefoobar.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at scala.io.Source$.fromFile(Source.scala:91)
at scala.io.Source$.fromFile(Source.scala:76)
at scala.io.Source$.fromFile(Source.scala:54)
at $line120.$read$$iw$$iw$Child.run(<console>:16)
at java.lang.Thread.run(Thread.java:745)
uh oh did not capture error
.Are你說,如果重寫孩子作爲try塊並拋出異常,如果我發現錯誤,Parent會得到該異常?我如何「拋出自己」這個例外?畢竟,在代碼中,拋出錯誤並上升到堆棧,並且沒有到達父代。在孩子中明確拋出錯誤會做到這一點? – user7938511