In: Computer Science
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)
Class stringArray
{
public string Name { get; set; }
}
class ManyCharactersException: Exception
{
public ManyCharactersException()
{
}
public ManyCharactersException(string name)
: base(String.Format("You entered too many characters"))
{
}
}
class Program
{
static void Main(string[] args)
{
StringArray newstringArray = null;
char str[1000];
While(1)
{
printf( "Enter a value :");
gets( str );
try
{
newstringArray = new stringArray();
newstringArray.Name = str;
ValidateArray(newstringArray);
}
catch(ManyCharactersException ex)
{
Console.WriteLine(ex.Message );
}
Console.ReadKey();
}
}
private static void ValidateArray(stringArray str)
{
if (strlen(str.Name > 20)
throw new ManyCharactersException(str.Name);
else if
(str.Name = “Done”)
Console.WriteLine("Goodbye");
Break;
else
Console.WriteLine(“you entered” );
Console.WriteLine(str.Name);
}
}