Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA Programming Design and implement a program that creates an exception class

ID: 3684925 • Letter: J

Question

JAVA Programming

Design and implement a program that creates an exception class called StringTooLongException, designed to be thrown when a string is discovered that has too many characters in it. In the main driver of the program, read strings from the user until the user enters “DONE”. If a string is entered that has too many characters (say20), throw the exception. The program catches the exeption and and handles the exception if it is thrown. Handle the exception by printing an appropriate message, and then continue processing more strings.

Explanation / Answer

StringTooLongException.java

public class StringTooLongException extends Exception{
   String str1;
   public StringTooLongException(String s){
       this.str1 = s;
   }
public String toString(){
return ("Output String = "+str1) ;
}  
}

StringDriver.java


public class StringDriver {

   /**
   * @param args
   * @throws StringTooLongException
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
      
       java.util.Scanner in = new java.util.Scanner(System.in);
       System.out.println("Please Enter the String (DONE for stop)");
       String s = "";
       while(true){
           try{
           s = in.next();
           if(s.equalsIgnoreCase("DONE")){
               break;
           }
           if(s.length() > 20){
               throw new StringTooLongException("String is entered that has too many characters");
           }
           }
           catch(StringTooLongException exp){
           System.out.println(exp) ;
           }
       }
   }

}

Output:

Please Enter the String (DONE for stop)
Suresh
dfsdfsdfsadfadsfadsfasdfadsfsd
Output String = String is entered that has too many characters
ssdffsdfsdf
sdfsadfasdfsadfasdf
sdfsdafasdfadsfsadfsdfasdfsd
Output String = String is entered that has too many characters
sdfsdfsdfsdf
sdfsdafsadfadsfadsfadserertewrtewrtert
Output String = String is entered that has too many characters
DONE