第一种方案:可以使用try来手动抛出异常,并打印错误信息
JavaBean bean = null;
try {
bean = new Gson().fromJson(string, JavaBean.class);
} catch (Exception e) {
e.printStackTrace();
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
LogUtils.e(str);
}
第二种方案:判断返回的数据是否为json格式
/**
* 判断是否是json结构
*/
public static boolean isJson(String value) {
try {
new JSONObject(value);
} catch (JSONException e) {
return false;
}
return true;
}
本文介绍了两种处理Java中异常的方法:一是通过try-catch结构手动抛出异常并记录错误信息;二是通过尝试将字符串转换为JSON对象来验证数据是否符合JSON格式。这两种方法对于提高程序的健壮性和数据处理的准确性都有重要作用。
1万+

被折叠的 条评论
为什么被折叠?



