Skip to main content

Throw in JAVA | User Defined Exception Handling in JAVA | Our Throw Our Catch Exception Handling in JAVA.

The length of the string is not according to given one then throw the user defined LengthMatchException and handles it appropriately.
CODING:
import java.util.*;//To use Scanner & InputMismatchException Class
class LenString
{
 public static void main(String[] args)
  {
    Scanner s=new Scanner(System.in);
    System.out.print("Enter Your Name: ");
    String name=s.nextLine();
     try
      {
        System.out.print("Length of "+name+": ");
        int l=s.nextInt();
      if(name.length()!=l)
        throw new LengthMatchException(); 
         else
        System.out.print("Correct!");
       }
    catch(LengthMatchException Ex)
       {
        System.out.print("Error : " + Ex.getMessage());
       }
   catch(InputMismatchException e)
    {
     System.out.print("Error->Input Numeric Value 0 to 9...");
    }
  }
}
class LengthMatchException extends Exception//User Defined Exception
 {
  LengthMatchException()
   {
    super("Length Of Name is Not Same.");
   }
  LengthMatchException(String msg)
   {
    super(msg);
   }

}

Comments