【问题标题】:scala try/catch not catching exceptionscala try/catch 没有捕捉到异常
【发布时间】:2017-01-04 21:43:35
【问题描述】:

我对此感到很困惑。这应该很简单,并且出乎意料。我查看了类似的 SO 线程,它们涉及延迟执行或其他与此处无关的问题。

仅供参考,这是 Scala 2.11.8 的版本。我正在调用 Apache Kafka 0.10.1.1 库:

  def deleteTopic(zookeeperHostPort: String, topicName: String): Unit = {
    try {
      // the following log statement does execute. No surprise.
      logger.info("deleteTopic1")

      // If I uncomment the following simple `throw`, it is caught as expected.
      // throw new java.lang.IllegalArgumentException("test")

      // The following TopicCommand.main throws an exception that isn't caught.
      TopicCommand.main(Array("--zookeeper", zookeeperHostPort, "--delete", "--topic", topicName))

      // the following log statement doesn't execute
      logger.info("deleteTopic2 (probably will not output)")
    } catch {
      case _: IllegalArgumentException => logger.info(s"Error deleting topic $topicName. It probably did not exist.")
      case e: Exception => logger.info(s"Error (${e.getClass.getName}) deleting topic $topicName. It probably did not exist.")
    }
    // the following log statement doesn't execute
    logger.info("deleteTopic3")
  }

产生一个未被捕获的异常:

[ScalaTest-run-running-KafkaStreamSuite] ERROR kafka.admin.TopicCommand$  - java.lang.IllegalArgumentException: Topic testTopic does not exist on ZK path 192.168.50.20:2181
    at kafka.admin.TopicCommand$.deleteTopic(TopicCommand.scala:166)
    at kafka.admin.TopicCommand$.main(TopicCommand.scala:68)
    at myapp.kafkautilities.AdminUtilities$.deleteTopic(AdminUtilities.scala:17)
    <snip>

【问题讨论】:

  • 异常可能是从另一个线程抛出的。
  • 您确定没有捕获该异常并且您看到的输出不是 Kafka 库内部正在进行的某种日志记录吗?

标签: scala exception


【解决方案1】:

Kafka 捕捉到异常,将其打印出来,然后做一些令人讨厌的事情 - System.exit。见https://github.com/apache/kafka/blob/0.10.1.1/core/src/main/scala/kafka/admin/TopicCommand.scala#L76

  ...
67:  else if(opts.options.has(opts.deleteOpt))
68:    deleteTopic(zkUtils, opts)
69:} catch {
70:  case e: Throwable =>
71:    println("Error while executing topic command : " + e.getMessage)
72:    error(Utils.stackTrace(e))
73:    exitCode = 1
74:} finally {
75:  zkUtils.close()
76:  System.exit(exitCode)
77:}

【讨论】:

    猜你喜欢
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 2016-01-26
    相关资源
    最近更新 更多