Questions tagged «custom-error-handling»

19
空检查链与捕获NullPointerException
Web服务返回巨大的XML,我需要访问它的深层嵌套字段。例如: return wsObject.getFoo().getBar().getBaz().getInt() 问题是getFoo(),getBar(),getBaz()可能所有的回报null。 但是,如果我null在所有情况下都进行检查,则代码将变得非常冗长且难以阅读。此外,我可能会错过某些领域的检查。 if (wsObject.getFoo() == null) return -1; if (wsObject.getFoo().getBar() == null) return -1; // maybe also do something with wsObject.getFoo().getBar() if (wsObject.getFoo().getBar().getBaz() == null) return -1; return wsObject.getFoo().getBar().getBaz().getInt(); 可以写吗 try { return wsObject.getFoo().getBar().getBaz().getInt(); } catch (NullPointerException ignored) { return -1; } 或将其视为反模式?
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.