dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Handling BindException in Java

Port BindExceptions can occur if a port is already occupied by some other process and you try to use it again. See an example of how it works and the mechanisms involved.


advertisement

Port BindExceptions can occur if a port is already occupied by some other process and you try to use it again.

Below is a simple example that demonstrates this and the mechanisms involved.

import java.net.*;
import java.io.*;

public class HandleBindException
{
   public static void main(String args[])
   {
      HandleBindException handleBindException = new HandleBindException();
      handleBindException.proceed();
   }
   
   private void proceed(){
      final int BINDING_PORT = 5666 ;
      ServerSocket firstServerSocket = null, secondServerSocket = null;
      try {
         firstServerSocket = new ServerSocket(BINDING_PORT);
         secondServerSocket = new ServerSocket(BINDING_PORT);
      } catch (BindException e) {
         System.out.println("BindException: " + e);
         if (firstServerSocket == null)
         {
            System.out.println("firstServerSocket is null. Further handling necessary.");
         }
         if (secondServerSocket == null)
         {
            System.out.println("secondServerSocket is null. Further handling necessary.");
         }
      } catch (IOException ioe) {
         System.out.println("IOException: " + ioe);
      }
   }
}

/*

Expected output:

[root@mypc]# java HandleBindException
BindException: java.net.BindException: Address already in use: JVM_Bind
secondServerSocket is null. Further handling necessary.

*/

 

Visit the DevX Tip Bank

 



   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date