未报告的异常UnknownHostException;必须被抓住或宣布被抛出 [英] unreported exception UnknownHostException; must be caught or declared to be thrown

查看:1682
本文介绍了未报告的异常UnknownHostException;必须被抓住或宣布被抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,如下所示。但是当我尝试编译代码时,我收到以下错误。

I have a code that is given below.However when I try to compile the code I get the following error.

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

我在代码中捕获了上述异常。我不知道为什么会发生这种情况。

I am catching the above exception in the code.I don't know why this is happening.?

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块中,以便被你的catch块有效捕获

this statement is outside of try{}, put it inside try block to be effectively caught by your catch block

这篇关于未报告的异常UnknownHostException;必须被抓住或宣布被抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆