Reputation: 1305
I'm currently writing a simple method to quickly build an HttpURLConnection and I am having some problems understanding the exceptions that occur. It currently looks like this:
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;
}
}
I catch and log the MalformedURLException and ProtocolException exceptions as I know it is impossible that they will occur. However I throw on the IOException that can be thrown by url.openConnection(). What is this exception? What causes it and how should my app behave when one occurs?
Thank you all very much, William
Upvotes: 2
Views: 5183
Reputation: 3549
MalformedURLException: When format of the URL is incorrect (e.g. URL = "?@fake") ProtocolException: indicate that there is an error in the underlying protocol (may be something like SSL certificate is not valid)
IOException You did not get MalformedURLException only suggests that structure of the string URL you provided is correct. It does not guarantee that respective host exists and is reachable. It also does not guarantee that there will be no issues during connecting to the host or while performing any read or write to that host. So while opening connection to required host if there is an issue (host is not reachable) or during handshake of connection there was read/write error, you may get IOException.
Upvotes: 4
Reputation: 3859
You should look at the Javadoc as a first stop. http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html
You should be able get the cause , where available, by inspecting the cause and message params of he thrown exception
Upvotes: 0
Reputation: 2866
Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations. Hope this helps
Upvotes: -1
Reputation: 1239
Problems with network connection - not being able to write to or receive from the underlying socket.
Upvotes: 1