gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:05:25 25 4
gpt4 key购买 nike

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

输出
Scala> 父()
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

最佳答案

考虑使用 Futures 来处理异步任务的结果

import ExecutionContext.Implicits.global
val resultFuture: Future[Unit] = Future { new Child.run }
resultFuture.onComplete (result: Try[Unit] => ...)

关于Scala:如何在子线程中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com