1

I tried to run this piece of code without an internet connection, expecting and IOException to trigger:

import java.net.*;
import java.io.*;

public class API_connect {

    public static void main(String[] args) {
        try {
            URL API = new URL("http://api.football-data.org");
            URLConnection API_connection = API.openConnection();
        }
        catch(MalformedURLException exception) {
            System.out.print(exception);
        }
        catch(IOException exception) {
            System.out.print(exception);
            System.out.print("is something going on here?");
        }                   
    }

}

And well... To my surprise nothing was printed, and I can't figure out why. Wouldn't a lack of internet connection be the main reason why an IOException is thrown here?

1
  • When printing exceptions I generally prefer to use printStackTrace() Commented Nov 17, 2017 at 19:03

1 Answer 1

6

openConnection() does not actually try to connect:

It should be noted that a URLConnection instance does not establish the actual network connection on creation. This will happen only when calling URLConnection.connect().

Try calling connect() on it.

Alternatively, you could try the following:

new URL(...).openStream().read();

That would actually try to read 1 byte from that url and would fail.

Sign up to request clarification or add additional context in comments.

7 Comments

I would add, he opens a connection, but not getting and outputing anything from that connection. Meaning: It works and you need to get and write something from that connection. Sometimes nothing is the best that can happen. In your code. You can't get any output if it works correctly.
I think, the OP was expecting some exception on a connection attempt. Both connect() and read() would produce an exception.
That did infact trigger the exception, thanks. Now I'm curious however as to why openConnection() would throw an IOException. If being offline doesn't trigger it, what would?
@RomanPuchkovskiy probably should make my own thread for this. But why does connect() and read() throw an exception?
openConnection() is defined in URL class that is not specific to only HTTP (where it may be costly to 'connect right away', but it can be used with file: protocol where 'a connection right away' makes sense. So I believe that the designers of openConnection() method allowed it throw an IOException to give it more flexibility (in regard with different implementations).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.