Java异常不会传播到Scala

时间:2017-02-17 19:07:01

标签: java mongodb scala

以下scala代码似乎抛出了一个java异常,但继续执行其他代码行:

object FirstMain {
  def main(args: Array[String]): Unit = {
    var mongoClient : MongoClient = MongoClients.create() // this is a java method
    println("hello")
    Thread.sleep(500)
    println("hello2")
}

控制台输出:

Feb 17, 2017 7:57:49 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Feb 17, 2017 7:57:50 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.AsynchronousSocketChannelStream$OpenCompletionHandler.failed(AsynchronousSocketChannelStream.java:253)

[...] // stacktrace

java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

[...] // stacktrace

hello 
hello2

我尝试使用try / catch块来处理异常,但是我获得了与第一个代码片段相同的输出。以下代码从不打印"做某事!" :

object FirstMain {
  def main(args: Array[String]): Unit = {
  try{
    var mongoClient : MongoClient = MongoClients.create()
  }
  catch {
    case e : MongoSocketOpenException => println("do Something")
  }
  println("hello")
  Thread.sleep(500)
  println("hello2")
  }
}

任何人都知道如何捕获scala中async java代码引发的异常?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

这与异步或scala几乎没有关系。您调用的方法是同步的。它不会返回Future或其他异步类型。您正在创建的客户端是异步的,但方法不是。您无法捕获异常的原因是因为Mongo可能已经捕获异常并且不会让它冒出来。