抛出异常,尽管我有catch子句

时间:2018-07-18 04:40:12

标签: android exception-handling kotlin

我有此代码:

fun String?.toDoubleOrZero(): Double
{
    if (null == this) return 0.0
    return try { this.toDouble() }     // <-- Line #67
    catch (e: NumberFormatException) { 0.0 }
    catch (e: java.lang.NumberFormatException) { 0.0 }  //Just to make sure
}

我显然已经处理过NumberFormatException。我什至还添加了Java的NumberFormatException。但是我仍然有很多这样的崩溃报告:

Fatal Exception: java.lang.NumberFormatException: Invalid double: "35°45'39.2"N"
       at java.lang.StringToReal.invalidReal(StringToReal.java:63)
       at java.lang.StringToReal.parseName(StringToReal.java:230)
       at java.lang.StringToReal.parseDouble(StringToReal.java:254)
       at java.lang.Double.parseDouble(Double.java:295)
       at *********.toDoubleOrZero(***.kt:67)
       at ...

这怎么可能?我需要做什么?

注意:我什至无法重现这种情况,我的代码在测试时可以正常运行,但是Crashlytics中有很多此类崩溃报告。

编辑:我发现只有在装有Android 4的HTC设备中才会发生这种情况!

2 个答案:

答案 0 :(得分:1)

  1. 在科特林,NumberFormatExceptiontypealias的{​​{1}},因此您不需要第二名。
  2. 由于您已经拥有java.lang.NumberFormatException,为什么还要为异常而烦恼?

    toDoubleOrNull()

  3. 我不认为您的代码是导致异常的原因,因此请对上面的代码进行测试并检查异常,我们将会看到。

答案 1 :(得分:0)

fun String?.toDoubleOrZero(): Double
{
   double value;
     if (null == this) {
        return 0.0 
     }
     return try {
      value = new Double(this.toString()); //typecast your value which is in **this** into double

                 **OR**

    value = Double.valueOf(this); //if **this** is String type;
    }     // <-- Line #67
    catch (e: NumberFormatException) {
      value = 0;
    }
    catch (e: java.lang.NumberFormatException) {
      value = 0;
    } 
}
相关问题