原因是编译器告诉类构造函数(URL)和方法(openConnection
..)抛出异常(在它们中定义signatures
)并采取一些必要的步骤。
您有 2 个选项:
Throw
检查的异常来自您的主要方法。
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.google.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " +
httpCon.getResponseCode());
}
或者
抓住那个Exception
,使用try catch block.
public static void main(String[] args) {
URL url;
HttpURLConnection httpCon;
try {
url = new URL("http://www.google.com");
httpCon = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + httpCon.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
}