gpt4 book ai didi

java - 未报告的异常 UnknownHostException;必须被捕获或宣布被抛出

转载 作者:行者123 更新时间:2023-11-29 05:39:48 24 4
gpt4 key购买 nike

我有下面给出的代码。但是,当我尝试编译代码时,出现以下错误。

MyClient.java:12: error: unreported exception UnknownHostException; must be caught or declared to be thrown
InetAddress address = InetAddress.getByName("localhost");

我在代码中捕获了上述异常。我不知道为什么会这样。?

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class MyClient {
public static void main(String[] args) {
InetAddress address = InetAddress.getByName("localhost");

int count = 0;
try {
/*
* Create a connection to the server socket on the server application
*/

Socket socket = new Socket(address, 9090);

/*
* Read and display the response message sent by server application
*/

ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
System.out.println("Created client socket and Input Stream Reader");
while (true) {
if (count < 1000) {
String message = (String) ois.readObject();
System.out.println("OFMessage: " + message);
count++;
} else {
break;
}
}

ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

最佳答案

InetAddress address = InetAddress.getByName("localhost");

此语句在 try{} 之外,将其放在 try block 内以被您的 catch block 有效捕获

关于java - 未报告的异常 UnknownHostException;必须被捕获或宣布被抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18040488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com