简体   繁体   中英

Java exception does not propagate to Scala

the following scala code seems to throw a java exception, but keeps on executing other lines of code :

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")
}

console output :

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

I tried using a try/catch block to deal with the exception but I get the same output as inthe fist code snippet. The following code never prints "do something !" :

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")
  }
}

Anyone knows how to catch exception thrown by async java code in scala ?

Thanks in advance for your help.

This has little to do with async or scala. The method you are calling is synchronous. It doesn't return a Future or other async type. The client you are creating is async but the method is not. The reason that you cannot catch the exception is because Mongo is likely already catching the exception and not letting it bubble up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM