Open In App

java.net.BindException in Java with Examples

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:

Method Summary 



  1. Methods inherited from class java.lang.Throwable: 
    addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, setStackTrace, toString.
     
  2. 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.net.BindException in Java with Examples
  
import java.io.*;
import java.net.*;
public class Ex_BindException {
  
    // Creating a variable PORT1 with arbitrary port value
    private final static int PORT1 = 8000;
  
    public static void main(String[] args)
        throws IOException
    {
  
        // Creating instance of the ServerSocket class
        // and binding it to the arbitrary port
        ServerSocket socket1 = new ServerSocket(PORT1);
  
        // Creating another instance of the ServerSocket
        // class and binding it to the same arbitrary
        // port,thus it gives a BindException.
        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.


Article Tags :