2013-08-04 177 views
1

我有一個代碼如下。但是,當我嘗試編譯代碼時,出現以下錯誤。未報告的異常UnknownHostException;必須被捕獲或被宣告爲被拋出

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(); 
     } 
    } 
} 

回答

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

這種說法是try{}之外,把它try塊內通過您的catch塊被有效地收集

相關問題