![](/img/trans.png)
[英]Unreported exception IOException, must be caught or declared to be thrown
[英]unhandled exception: IOException must be caught or thrown
所以最近我開始用Java在自己的IRC客戶端/服務器上工作。 NetBeans說我有一個未處理的IOException。 但是,查看我的代碼,我做了一個try-catch塊來捕獲IOException。 這是我的代碼:
package some.package.name;
import java.io.IOException;
import java.net.ServerSocket;
public class IRCServer extends ServerSocket {
private ServerSocket server;
private int port;
/**
* <p>Main constructor. Provides default port of 6667</p>
*/
public IRCServer() {
this(6667);
}
/**
* <p>Secondary constructor. Uses port defined by either user or Main constructor</p>
*
* @param port The port to listen to for the server
*/
public IRCServer(int port) { //This is where NetBeans show the error
this.port = port;
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.err.println("IOException caught\n" + e.toString());
}
}
/**
* <p>Overrides parent String toString()</p>
*
* @return PORT the server is listening to
*/
@Override
public String toString() {
return "PORT: " + this.port;
}
}
請注意, try...catch
中的IOException
實際上是java.io.IOExecption
。
是什么導致編譯錯誤?
編輯:我已經在Eclipse中嘗試了相同的代碼,並通過cmd對其進行了編譯。 它仍然給出相同的錯誤
您的問題是您的類都擴展了ServerSocket
並具有ServerSocket
字段。 這意味着理論上對於IRCServer
每個實例,您都有兩個 ServerSocket
實例。 一種是IRCServer
本身,因為它對其進行了擴展,另一種是您命名為server
的嵌入式ServerSocket
。
這本身就是一個嚴重的設計問題-如果您實際上不以任何方式依賴於其原始功能,則無需擴展類。 而且,如果您打算將IRCServer
用作ServerSocket
,則不應在其中嵌入其他server
。 this
將成為您的server
。
但是,導致編譯錯誤的問題是每個構造函數都隱式或顯式調用super()
構造函數。 如果原始類具有no-args構造函數-並且確實存在-那么如果您自己無法調用super(...)
,它將為您完成。
但是, ServerSocket
的構造函數聲明為:
public ServerSocket() throws IOException
和
public ServerSocket(int port) throws IOException
這意味着對super()
構造函數的隱式調用就在try...catch
之前發生,並引發一個已檢查的異常。 這意味着您必須在throws IOException
聲明自己的構造函數,因為無法用try...catch
包圍super()
調用。
我的建議是適當地擴展類或委托而不擴展。 正確擴展意味着沒有server
變量。 您的構造函數將如下所示:
/**
* <p>Main constructor. Provides default port of 6667</p>
*/
public IRCServer() throws IOException {
this(6667);
}
/**
* <p>Secondary constructor. Uses port defined by either user or Main constructor</p>
*
* @param port The port to listen to for the server
*/
public IRCServer(int port) throws IOException {
super(port);
this.port = port;
}
正確地委派將意味着保留大部分原始代碼,但刪除extends ServerSocket
,那么您將無法多態使用IRCServer
作為ServerSocket
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.