IOException Java

Luc*_*cas 1 java exception

我尝试在没有互联网连接的情况下运行这段代码,期望和IOException触发:

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?");
        }                   
    }

}
Run Code Online (Sandbox Code Playgroud)

好吧......令我惊讶的是没有打印出来,我无法弄清楚原因.不会缺少互联网连接是导致IOException抛出的主要原因吗?

Rom*_*kiy 6

openConnection() 实际上并没有尝试连接:

应该注意,URLConnection实例在创建时不建立实际的网络连接.只有在调用URLConnection.connect()时才会发生这种情况.

试着呼吁connect()它.

或者,您可以尝试以下方法:

new URL(...).openStream().read();
Run Code Online (Sandbox Code Playgroud)

那实际上会尝试从该URL读取1个字节并且会失败.