簡體   English   中英

如何防止java.util.Date.toString崩潰?

[英]How to prevent crash from java.util.Date.toString?

有時,以下代碼會導致Android應用崩潰:

try {
    (new Date()).toString());
} catch (Exception ex) {
    ...
}

堆棧跟蹤:

java.lang.AssertionError: 
  at android.icu.impl.TimeZoneNamesImpl$ZNames.getNameTypeIndex (TimeZoneNamesImpl.java:724)
  at android.icu.impl.TimeZoneNamesImpl$ZNames.getName (TimeZoneNamesImpl.java:790)
  at android.icu.impl.TimeZoneNamesImpl.getTimeZoneDisplayName (TimeZoneNamesImpl.java:183)
  at android.icu.text.TimeZoneNames.getDisplayName (TimeZoneNames.java:261)
  at java.util.TimeZone.getDisplayName (TimeZone.java:405)
  at java.util.Date.toString (Date.java:1066)

顯然,錯誤無法捕獲。 有辦法防止這種情況嗎?

如果你使用新的Date()來獲取AssertionError,這似乎很奇怪並且可能與Android 8問題相關而不是代碼,你可以使用Java 8中的 java.time而不是java.util.Date,如下所示:

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

DateTimeFormatter formatter = DateTimeFormatter
    .ofPattern("yyyy/MM/dd HH:mm:ss")
    .withZone(ZoneId.systemDefault()); //you must add time zone because of Instant

Instant currentTimestamp = Instant.now();

System.out.print(formatter.format(currentTimestamp));          

非常奇怪的問題......

BTW沒有拋出異常,而是從Error擴展的AssertionError

你可以使用:

try {
    (new Date()).toString());
} catch (AssertionError ex) {// or Error or Throwable
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM