0

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.

Antonin
  • 879
  • 2
  • 10
  • 27
  • You should check this one http://stackoverflow.com/a/40814641/539864 – xiumeteo Feb 17 '17 at 19:13
  • 2
    Possible duplicate of [How to catch exception when creating MongoClient instance](http://stackoverflow.com/questions/40813060/how-to-catch-exception-when-creating-mongoclient-instance) – xiumeteo Feb 17 '17 at 19:14
  • Definitely a duplicate, as the problem is note related to scala-java interfacing. Should I remote the question then ? – Antonin Feb 18 '17 at 11:28

1 Answers1

3

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.

dres
  • 1,172
  • 11
  • 15
  • Thank you @dress I see that this exception can't be catched from my code, and that I have to test the connection the first time I use it in my code, thanks to : [this related question](http://stackoverflow.com/questions/40813060/how-to-catch-exception-when-creating-mongoclient-instance) – Antonin Feb 18 '17 at 11:31