In: Computer Science
To be Completed in C#
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!
using System;
class MainClass {
static void Main(string[] args) {
Console.WriteLine("Enter strings. When finished enter DONE");
string s;
// reading & checking strings in do while loop
do{
s = Console.ReadLine();
try {
// checking if length is less than or equal to 20
// if not throwing expections
if ( s.Length <= 20 )
Console.WriteLine("You entered : "+s);
else
throw new ManyCharactersException("You entered too many characters");
} catch(ManyCharactersException e) {
// printing the exception message
Console.WriteLine(e.Message);
}
}while(!s.Equals("DONE"));
Console.WriteLine("Good bye!");
}
}
// user defined exception
public class ManyCharactersException: Exception {
public ManyCharactersException(string message): base(message) {
}
}
Code
Output