Reputation: 2300
I have this code:
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
}
I have clearly handled NumberFormatException
. I even added Java's NumberFormatException
to be sure. But still I have many crash reports like this:
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 ...
How is this possible and what do I need to do?
Note: I can't even reproduce this situation, my code works correctly when I test it, however I have lots of these crash reports in Crashlytics.
Edit: I found out that this happens only in HTC devices with Android 4!
Upvotes: 0
Views: 152
Reputation:
NumberFormatException
is a typealias
for java.lang.NumberFormatException
so you don't need the 2nd.Why bother with exceptions since you already have toDoubleOrNull()
?
fun String?.toDoubleOrZero(): Double {
val result = this?.toDoubleOrNull()
return if (result == null) 0.0 else result
}
I don't believe that your code is the reason for the exception, so put the above code to test and check for exceptions and we'll see.
Upvotes: 1
Reputation: 1159
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;
}
}
Upvotes: 0