Many methods in the Socket class throws some exceptions when declaring them. These exceptions are subclasses of IOException. The most thrown in the Socket class method is SocketException, and the other seven exceptions can be thrown by the Socket class method. The inheritance relationship of these exceptions is shown in 1. The exception described in the gray background box is the exception that may be thrown by the Socket class method.
Figure 1 Abnormal class inheritance relationship diagram
- Public class IOException extends Exception
This exception is the parent class of all exceptions thrown in the Socket class method. Therefore, you only need to catch the Exception when using the Socket class. Of course, to catch the Exception of methods in other classes at the same time, you can also directly catch the Exception.
Public class SocketException extends IOException
This exception is most frequently used in Socket class methods. It also represents all network-related exceptions. However, if you want to know which type of exceptions occur, You need to capture more specific exceptions.
Public class ConnectException extends SocketException
A ConnectException exception usually occurs when the server is busy and does not respond or the corresponding listening port of the server is not opened. The following statement throws a ConnectException exception.
Socket socket = new Socket ("www.ptpress.com.cn", 1234 );
Public class BindException extends SocketException
This exception occurs when multiple Socket or ServerSocket objects are bound to the same port and the SO_REUSEADDR option is not enabled. The following four statements throw a BindException exception:
Socket socket1 = new Socket ();
Socket socket2 = new Socket ();
Socket1.bind (new InetSocketAddress ("127.0.0.1", 1234 ));
Socket2.bind (new InetSocketAddress ("127.0.0.1", 1234 ));
Public class NoRouteToHostException extends SocketException
This exception occurs when the host cannot be found in the firewall or route.
Public class UnknownHostException extends IOException
This exception is thrown when the domain name is incorrect. The following statement throws an UnKnownHostException:
Socket socket1 = new Socket ("www.ptpress123.com.cn", 80 );
Public class ProtocolException extends IOException
This exception is not often thrown. For unknown reasons, the TCP/IP packet is damaged and a ProtocolException exception is thrown.
Public class SocketTimeoutException extends InterruptedIOException
If the server still does not respond after the connection timeout and data read timeout, the connect or read method throws a SocketTimeoutException exception.