【发布时间】:2012-05-14 14:28:06
【问题描述】:
我对以下代码有疑问。首先,我是 Java 的新手,有其他几种语言的经验。
当我在 Android 上运行以下命令时,它在 "in.close();" 处出错,跳转到 catch 块并运行 Return "";问题是,该函数没有返回空字符串,它成功返回了正确的 json 数据,即使调试器说它没有运行 return json,而是运行 return "";
public void fetch() {
// Get the JSON of the image gallery
String json = getJSON();
// json somehow has the actual correct json data and not an empty string!
};
private String getJSON() {
try {
// Create a URL for the desired page
URL url = new URL("http://imgur.com/gallery.json");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String json = in.readLine();
in.close();
return json; // <-- debugger doesn't break here!
}
catch(Exception e) {
Log.e("getJSON", e.getMessage());
return ""; // <-- debugger breaks here! Cat Log shows nothing!
}
}
我将完全相同的代码复制到 Java 控制台中,这样我就可以输出错误消息并在带有断点的调试器中观察它,并且代码执行时不会出错。
try {
// Create a URL for the desired page
URL url = new URL("http://imgur.com/gallery.json");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String json = in.readLine();
in.close();
System.out.println(json);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
到底发生了什么?为什么我的代码在 Java 控制台中运行时在 Android 上运行会出错?为什么当它出错时它不返回错误应该返回的内容;和空字符串?如何在 Android 中查看错误消息?
【问题讨论】:
-
您是否在清单文件中设置了 Internet 权限?
-
你确定你得到一个错误?您可以在您的异常上调用
e.printStackTrace()以获取确切的异常类型以及它发生在哪一行。这适用于常规 java 和 Android(在 android 上它显示在 LogCat 中)。 -
我在返回之前在我的 catch 块中添加了 e.printStackTrace(),但我的 LogCat 中没有显示任何内容。如果函数正确返回 json,并且没有输出错误,那么为什么调试器会在我在 catch 块中返回的断点处中断?