【发布时间】:2013-03-21 18:55:20
【问题描述】:
我目前正在编写一个简单的方法来快速构建一个 HttpURLConnection,但我在理解发生的异常时遇到了一些问题。目前看起来是这样的:
public static HttpURLConnection buildConnection(String urlString) throws IOException{
try{
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000 /* 10 seconds */);
connection.setConnectTimeout(10000 /* 10 seconds */);
return connection;
} catch (MalformedURLException e){
// Impossible - All network URLs are taken from String resources
Log.w(LOG_LABEL, "URL \"" + urlString + "\" was malformed");
e.printStackTrace();
return null;
} catch (ProtocolException e){
// Impossible - "GET" is a valid Request method
e.printStackTrace();
return null;
}
}
我捕获并记录 MalformedURLException 和 ProtocolException 异常,因为我知道它们不可能发生。但是我抛出了 url.openConnection() 可能抛出的 IOException。这是什么异常?是什么原因造成的?发生这种情况时我的应用应该如何表现?
非常感谢大家, 威廉
【问题讨论】:
标签: java android exception-handling httpurlconnection