我正在使用此代码来检索html页面并解析它
while(doc == null && retry<5){
retry++;
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
Log.e("ReleaseInfo", "JSoup get didnt get a document", e);
}
一旦检索到文档,我就会使用它获取一些信息并测试null。
overview = doc.select("div#object-overview").last();
if(overview != null){
paragraph = overview.select("p").last();
if(paragraph != null){
Log.v("Paragraph", paragraph.text());
}else{
Toast.makeText(releaseInfo.this, "No over view content", Toast.LENGTH_SHORT);
}
}
else{
}
featureList = doc.select("div.callout-box").last();
if(featureList != null){
Log.v("OverView", featureList.text());
如您所见,我正在使用日志语句捕获错误。 IOException告诉我这个
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): JSoup get didnt get a document
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): java.net.SocketTimeoutException
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at org.apache.harmony.luni.net.PlainSocketImpl.read(PlainSocketImpl.java:564)
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at org.apache.harmony.luni.net.SocketInputStream.read(SocketInputStream.java:88)
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at java.io.InputStream.skip(InputStream.java:258)
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at org.apache.harmony.luni.net.SocketInputStream.skip(SocketInputStream.java:93)
08-17 12:54:11.535: ERROR/ReleaseInfo(5960): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl$ChunkedInputStream.skipOutstandingChunks(HttpURLConnectionImpl.java:374)
我怎样才能使我的代码防范此错误,以便在文档未被检索时不强制关闭?
此外,我想抓住并回应导致我的申请强制关闭的此异常。
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): JSoup get didnt get a document
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): java.io.IOException: 404 error loading URL http://pc.gamespy.com/web-games/parking-wars-2/
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:387)
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:364)
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:143)
08-17 16:27:29.245: ERROR/ReleaseInfo(8641): at org.jsoup.helper.HttpConnection.get(HttpConnection.java:132)
答案 0 :(得分:4)
您显示的日志条目表示您捕获了异常并将其作为错误打印到日志中,正如您所期望的那样。这些条目都不应强行关闭您的应用。还有其他条目吗?例如,如果你在5次重试之后仍然没有建立连接,那么'doc'将等于null,而下面的行将导致未被捕获的nullPointerException然后将关闭你的应用程序:
overview = doc.select("div#object-overview").last();