我原以为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)
输出标量> Parent()
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
Run Code Online (Sandbox Code Playgroud)
考虑使用 Futures 来处理异步任务的结果
import ExecutionContext.Implicits.global
val resultFuture: Future[Unit] = Future { new Child.run }
resultFuture.onComplete (result: Try[Unit] => ...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1652 次 |
| 最近记录: |