我有一个需要返回 JSONObject 的方法:
public JSONObject getDayJson(Date date) {
...
a few lines of code
...
return new JSONObject("..");
}
但是,这给了我一个错误,因为我需要捕获实例化 JSONObject 时可能发生的任何异常:
public JSONObject getDayJson(Date date) {
try {
...
a few lines of code
...
return new JSONObject("..");
} catch (Exception e) {
// need a return statement here!
}
}
这会产生另一个错误,因为在 catch block 中我没有返回正确的对象类型(JSONObject)。如果我在 catch 中实例化另一个 JSONObject,我需要嵌套另一个 catch 语句?!
最佳答案
您应该更好地考虑如果发生异常您想要做什么,但一种选择是强制非异常调用构造函数。
public JSONObject getDayJson(Date date) {
try {
...
a few lines of code
...
return new JSONObject("..");
} catch (Exception e) {
// doesn't throw another exception
return new JSONObject(new HashMap());
}
}
关于java - Android Java JSON 未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31631398/