java.net.BindException in Java with Examples
Last Updated :
03 Mar, 2021
The java.net.BindException is an exception that is thrown when there is an error caused in binding when an application tries to bind a socket to a local address and port. Mostly, this may occur due to 2 reasons, either the port is already in use(due to another application) or the address requested just cannot be assigned to this application. The BindException inherits from the SocketException class, thus showing there is an error related to the socket creation or access.
Constructors
The following constructors are available for BindException:
- BindException(): Creates a simple instance of the BindException class with no detailed message
- BindException(String msg): Creates an instance of the BindException class with the specified message as the reason why the bind error occurred.
Method Summary
- Methods inherited from class java.lang.Throwable:
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, setStackTrace, toString.
- Methods inherited from class java.lang.Object:
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait.
HIERARCHY OF java.net.BindException
Example:
In the example below, we have created a class Ex_BindException to demonstrate the BindException :
Java
import java.io.*;
import java.net.*;
public class Ex_BindException {
private final static int PORT1 = 8000 ;
public static void main(String[] args)
throws IOException
{
ServerSocket socket1 = new ServerSocket(PORT1);
ServerSocket socket2 = new ServerSocket(PORT1);
socket1.close();
socket2.close();
}
}
|
Output:
In the above code, we first created an instance of the ServerSocket class using the specified port. That instance is successfully bound. However, when on the creation of another instance using the same port, a BindException occurs as the port is already bound to the other Socket. Here, we can simply use another arbitrary port (which is not in use) for the second socket to get rid of this exception.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...