问题描述
使用以下代码时:
scala> Future { null } onComplete { case Success(v) => v.toString }
Scala引发以下异常:
Scala throws the following exception:
scala> java.lang.NullPointerException
at $line14.$read$$iw$$iw$$anonfun$2.apply(<console>:11)
at $line14.$read$$iw$$iw$$anonfun$2.apply(<console>:11)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
at scala.concurrent.impl.ExecutionContextImpl$$anon$3.exec(ExecutionContextImpl.scala:107)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
这样就行了,因为我没有处理任何异常。问题是我的应用程序完全挂起。
This would be OK, since I am not handling any exceptions. The problem is that my application hangs completely.
我使用 concurrent.ExecutionContext.Implicits.global
onComplete
在此全局执行上下文中执行。问题是,似乎执行上下文停止接受任何工作,并且应用程序刚刚挂起。
I am using concurrent.ExecutionContext.Implicits.global
and I think onComplete
is executed in this global execution context. The problem is that it seems like the execution context stops accepting any work and and the application just hangs.
我必须明确使用 try。 .. catch
,以便在 onComplete
?中发生意外事件时保护我的应用程序?
Do I have to explicitly use try ... catch
so that I protect my app in case something unexpected happens in onComplete
?
谢谢
推荐答案
IIRC,这只是最早实现的问题。
IIRC, this was an issue only in the very earliest implementation.
您可以提供处理程序或记者:
You can supply a handler or "reporter":
scala> import util._
import util._
scala> import concurrent._
import concurrent._
scala> ExecutionContext.fromExecutor(null, (t: Throwable) => println(s"Hi, $t"))
res0: scala.concurrent.ExecutionContextExecutor = scala.concurrent.impl.ExecutionContextImpl@221a3fa4
scala> implicit val x = res0
x: scala.concurrent.ExecutionContextExecutor = scala.concurrent.impl.ExecutionContextImpl@221a3fa4
scala> Future { null } onComplete { case Success(v) => v.toString }
<console>:16: warning: match may not be exhaustive.
It would fail on the following input: Failure(_)
Future { null } onComplete { case Success(v) => v.toString }
^
Hi, java.lang.NullPointerException
scala>
一切都处理。
这篇关于处理意外的异常scala期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!