Scala: How to catch exceptions in child threads

exception, scala

Solution

Consider using Futures to handle result of async task

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

Problem

I had thought that the `Try` catches cross-Thread exceptions as in example below. I guess not: so how do I catch exceptions in spawned child threads? ``` // 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") } } ``` Output scala> 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 ```

Original source