这是Asynctask
方法:
public class Read extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
sUrl = sUrl.trim();
json = lastTweet(sUrl);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
}
}
以及相关的 lastTweet 方法:
public JSONObject lastTweet(String username)
throws ClientProtocolException, IOException, JSONException {
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}
}
所有这些代码都工作正常。目前没有任何问题。但是,我想做一些小的修补。当HTTP 传输期间连接丢失时,RemoteException
会抛出 a 并且应用程序崩溃。
我试图在Async
方法中处理异常但无法这样做。
有什么办法可以处理这种异常?