如何在 Java (Android) 中捕获 "Could not deserialize object." 异常?

How to catch a "Could not deserialize object." exception in Java (Android)?

假设我正在将大量数据从服务器转换为自定义本地 java 对象。 POJO 有一个 int 变量,这是我希望从服务器获得的。只是,假设某些数据将数字列为字符串而不是整数。我有一个 for 循环设置如下:

for (Object document : DataSentFromServer) {                                   
   MyObjectClassArrayList.add(document.toObject(MyObject.class));
}

所以 99% 的文档将 int 作为 int,但有一个文档将其作为 String。因此,当 for 循环到达该文档时,它会抛出 java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type java.lang.String to int 我知道我需要更新服务器上的数据,我已经这样做来解决这个问题。

我的问题是: 我如何创建一个 catch 块或其他东西,它会简单地跳过服务器中与我的对象的数据模型不匹配的文档 class?因为我不希望我的客户端应用程序在服务器数据出现问题时崩溃。

用 try catch 块简单包围函数:

for (Object document : DataSentFromServer) {  
    try{                                 
       MyObjectClassArrayList.add(document.toObject(MyObject.class));
    }catch(RuntimeException e){
      //do something with the bad data if you wish.
    }
}

关于@Marksim Novikov 回答的一些更新。

 for (Object document : DataSentFromServer) {  
try{                                 
   MyObjectClassArrayList.add(document.toObject(MyObject.class));
}catch(RuntimeException e){
  //continue will skip the current iteration and go to next iteration
   continue;
  }
}

因此,如果您 运行 进入运行时异常,它将跳过该迭代并转到下一个。