简体   繁体   English

Java异常不会传播到Scala

[英]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 : 以下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")
}

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. 我尝试使用try / catch块来处理异常,但是我得到的输出与第一段代码相同。 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 ? 有谁知道如何捕获Scala中异步Java代码引发的异常?

Thanks in advance for your help. 在此先感谢您的帮助。

This has little to do with async or scala. 这与异步或scala无关。 The method you are calling is synchronous. 您正在调用的方法是同步的。 It doesn't return a Future or other async type. 它不返回Future或其他异步类型。 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. 之所以无法捕获该异常,是因为Mongo可能已经捕获了该异常,并且没有让它冒出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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