In: Computer Science
*In Java please!
EXCEPTION HANDLING
Concept Summary:
1. Exception handling
2. Class design
Description
Write a program
that creates an
exception class called
ManyCharactersException, designed
to be thrown when
a string is
discovered that has
too many characters
in it.
Consider a program
that takes in the
last names of
users. The driver
class of the program
reads the names (strings) from
the user until the
user enters "DONE".
If a name is
entered
that has more than
20 characters, throw
the exception.
Design the program
such that it
catches and handles
the exception if it
is thrown. Handle
the exception by
printing an appropriate
message, and then
continue processing more
names by getting more
inputs from the user.
Note: Your program
should exit only
when the
user enters "DONE".
SAMPLE OUTPUT:
Enter strings. When finished enter DONE
Short string
You entered: Short string
Medium size string
You entered: Medium size string
Really really long string, someone stop me!
You entered too many characters
DONE
You entered: DONE
Good bye!
RUBRICS:
Design the Exception class
(20 points):
Constructing the Try…
Catch… Throw within the
Driver class (40 points)
Constructing Error Message
for the Exception
class (10 points)
Constructing other error
messages (20 points)
Loop and other
constructs to complete
the program (10 points)
Solution - Required code has been provided below along with the output. Comments have been placed in the code to depict the functionality of the various statements/functions.
There is an exception class defined, in which the constructor has been defined to print the required error message when the string length is too long. Code runs until user enters "DONE" (all in caps)
Code
import java.util.*;
//Except class
class ManyCharactersException extends Exception
{
//Definded Constructor to print error when exception is thrown
ManyCharactersException(String s)
{
System.out.println(s);
}
}
public class ExceptionTest {
public static void main (String args[])
{
//Scanner to read user input
Scanner reader = new Scanner(System.in);
//input from user with a loop
System.out.println("Enter strings. When finished enter DONE");
String s = reader.nextLine();
while (s.equals("DONE") == false)
{
try
{
if (s.length() > 20)
{
//throw the exception with the message
throw new ManyCharactersException("You entered too many characters");
}
else
{
System.out.println("You entered: "+s);
s= reader.nextLine();
}
}
catch(ManyCharactersException exp)
{
s= reader.nextLine();
}
}
System.out.println("You entered: "+s);
System.out.println("Good bye!");
}
}
Output: user input has been shown in purple colour.
java ExceptionTest
Enter strings. When finished enter DONE
Short string
You entered: Short string
medium string
You entered: medium string
very very very long
string
You entered too many characters
DONE
You entered: DONE
Good bye!