Prevent second object creation with Exception Handling

Q. Write a Java program which creates only one object. If user attempts to create second object, he should not be able to create it. (Using Exception Handling).

Answer:

This example shows that how to create custom exception in java. When user try to create more than one object, it throws exception.

NotMoreException.java

class NotMoreException extends Exception
{
     NotMoreException()
     {
          super("No more than 1 object");
     }
}


Test.java

class Test
{
     static int cnt=0;
     Test() throws NotMoreException
     {
          if (cnt == 0)
          {
               cnt++;
          }
          else
               throw new NotMoreException();
     }
}


Demo.java

class Demo
{
     public static void main(String[] args)
     {
          try
          {
               Test t1 = new Test();
               Test t2 = new Test();
               Test t3 = new Test();
          }
          catch (NotMoreException ex)
          {
               System.out.println(ex);
          }
     }
}


Output:

when we try to run this program it generates the exception.

NotMoreException: No more than 1 object