我已经实现了一个执行某些网络请求的try块但是每当它抛出一个例外有一个超时时,android应用程序会显示一条消息Saying
抱歉:该应用已停止意外,请重试。
向用户呈现的唯一选项是强制关闭按钮。我想捕获此异常并简单显示我自己的错误消息,让用户再次尝试连接,而不是用户必须关闭应用程序。
以下是代码:
我想要做的就是在捕获到异常后返回null,并且调用它的类将执行它自己的错误处理,如下所示:
if(postRequest == null){ display error message}
private HttpResponseObject PostRequest() {
//int response = 0;
String responseBody = "";
HttpResponseObject response = new HttpResponseObject();
try {
Log.d(TAG, "IN POST_REQUEST_METHOD");
Log.d(TAG, "URL : " + url);
httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1);
//httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5);
Log.d(TAG, "httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);");
post = new HttpPost(url);
// ClientConnectionRequest connRequest = new ManagedClientConnection();
// post.setConnectionRequest((ClientConnectionRequest) connRequest.getConnection(3000, TimeUnit.MILLISECONDS));
ByteArrayEntity entity = new ByteArrayEntity(data.getBytes());
entity.setChunked(true);
post.setEntity(new StringEntity(data));
HttpResponse httpResponse = httpclient.execute(post);
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
// indicate that the content of this entity is no longer
// required
response.setResponseBody(EntityUtils.toString(resEntity));
Header[] header = httpResponse.getAllHeaders();
Log.d(TAG, "httpResponse.getAllHeaders() = " + header[0].getName());
response.setResponseHeader(httpResponse.getAllHeaders().toString());
resEntity.consumeContent();
}
// release all recources from the httpClient object
httpclient.getConnectionManager().shutdown();
response.setResponseCode(httpResponse.getStatusLine().getStatusCode() ) ;
Log.d(TAG, "responseBody = " + response.getResponseBody());
Log.d(TAG, "response code = " + response.getResponseCode());
Log.d(TAG, "response header = " + response.getResponseHeader());
return response;
} catch (SocketTimeoutException e) {
e.printStackTrace();
Log.d(TAG, "SocketTimeoutException e = " + e.toString());
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "IOException e = " + e.toString());
return null;
}
}
答案 0 :(得分:1)
由于未捕获的异常,将显示“强制关闭”对话框。由于您没有自己抛出已检查的异常,这是由于运行时异常,很可能是空指针异常。这意味着您的代码中存在导致此错误而不是网络错误的错误。
为了找到问题,您需要知道抛出的异常的类型及其消息。您可以在LogCat中看到这些 - 如果您使用的是Eclipse,则可以在调试透视图中找到它。