【问题标题】:Why is this still throwing the exception?为什么这仍然抛出异常?
【发布时间】:2018-12-29 15:56:04
【问题描述】:

我有一个 kotlin 代码的 sn-p,我实际上是在尝试忽略闭包内的异常:

val remainderParts = arrayOf("/Company/Employees/Employee[Name='Michael", "Scott']/Salary", "45000")
var xpath: XPathExpression = (1..remainderParts.size).mapNotNull {
        try {
          XPathFactory.newInstance().newXPath().compile(remainderParts.subList(0, it).joinToString(" "))
        }
        catch (e: TransformerException) {
          null
        }
      }.first()

但是当代码运行时,TransformerException 无论如何都会被抛出块外。怎么回事?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    您捕获了错误的异常。你要赶上XPathExpressionException

    val remainderParts = listOf("/Company/Employees/Employee[Name='Michael", "Scott']/Salary", "45000")
    var xpath: XPathExpression = (1..remainderParts.size).mapNotNull {
        try {
            XPathFactory.newInstance().newXPath().compile(remainderParts.subList(0, it).joinToString(" "))
        }
        catch (e: XPathExpressionException) {
            null
        }
    }.first()
    

    如果您不确定要捕获哪个异常,请使用Exception,它是所有异常的基类,并输出如下类型:

    // ...
    catch (e: Exception) {        
        println(e::class.simpleName) // XPathExpressionException
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2014-07-09
      • 2015-12-24
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多