【发布时间】:2014-12-04 04:41:53
【问题描述】:
我有以下代码,用于读取来自第三方的消息如果我对我得到的每个值使用 try catch 而不丢失任何值(Null 值),则中间的一些值并停止打印它们。我的问题是,除了对每一行都使用 try catch 之外,还有其他选择吗?
try{
printmsg.setGatepass(tosPrint.get("gatepass").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
printmsg.setTransactionType(tosPrint.get("transactionType").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
printmsg.setContainer(tosPrint.get("container").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
printmsg.setSsco(tosPrint.get("ssco").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
printmsg.setWgt(tosPrint.get("wgt").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
printmsg.setTruckingcmpny(tosPrint.get("truckingCompany").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
printmsg.setIssuetime(tosPrint.get("issueTime").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
printmsg.setLicense(tosPrint.get("driverLicense").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
printmsg.setChasis(tosPrint.get("chasis").toString());
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}try{
descNodes = tosPrint.getJSONObject("description");
linelist = descNodes.getJSONArray("eachLine");
printmsg.setDescription_lines(new String[linelist.length()]);
for (int i=0;i<linelist.length(); i++)
{
printmsg.getDescription_lines()[i]= linelist.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
LogWriter.LogErrorMessage(e);
}
假设如果我有 gatepass、transactionType、container、ssco、driverLicense、chasis 的值并且缺少一些值,例如 wgt、issueTime、truckingCompany,如果不使用 try catch 和使用 try catch,我可以打印到 ssco我能够打印所有值,所以如果没有任何值(即 null),是否有任何选项不使用 try catch 块的数量如何实现打印所有值。
【问题讨论】:
-
使用像 GSON 这样的库。并且不要使用像上面这样的反模式;它让我的眼睛流血,而且会非常缓慢。
-
异常处理是针对异常的,不是针对正常的控制流的。
-
将此提交给codereview.stackexchange.com。不过请注意,那里的人不会善待重复的逻辑和异常滥用。
-
如何在java中使用GSON将xml转换为json
标签: java xml json performance try-catch