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.