以前は、Javaのすべてのネットワーク・エラーはSocketExceptionを発生させていましたが、エラーの原因については十分な情報を提供しませんでした。たとえば、リモート・コンピュータが接続を拒否したのか(そのポート上で何も待機していないのか)、またはホストに到達できなかったのか(接続の試みがタイムアウトになったのか)といった原因を特定できませんでした。JDK 1.1では、洗練されたエラー・レポートを提供する3つの新しいクラスが追加されました。
ローカル・ポートが使用中、または要求バインド・アドレスがローカルに割当てできなかった。
public class BindException extends SocketException { ... }
接続がリモート・ホストで拒否されたとき、例外が発生する(すなわち、そのポートをどのプロセスも監視していない)。
public class ConnectException extends SocketException { ... }
接続の試みがタイム・アウトしたか、そうでなければリモート・ホストに到達できない。
public class NoRouteToHostException extends SocketException { ... }
import java.net.*; ... Socket s = null; try { s = new Socket("example.org", 80); } catch (UnknownHostException e) { // check spelling of hostname } catch (ConnectException e) { // connection refused - is server down? Try another port. } catch (NoRouteToHostException e) { // The connect attempt timed out. Try connecting through a proxy } catch (IOException e) { // another error occurred }
import java.net.*; ... ServerSocket ss = null; try { /* try to bind to local address 192.0.2.254 */ InetAddress in = InetAddress.getByName("192.0.2.254"); int port = 8000; int backlog = 5; ss = new ServerSocket(port, backlog, in); } catch (BindException e) { // port 8000 in use, or can't bind to 192.0.2.254 as a local address } catch (SocketException e) { // another error occurred }