96.0k views
1 vote
Write C# program that will read name from keyboard and display it on screen. The program should throw an exception when the length of name is more than 15 character.

User Esma
by
5.9k points

1 Answer

1 vote

Answer:

static void Main(string[] args)

{

try

{

Console.Write("Enter your name: ");

string name = Console.ReadLine();

if (name.Length > 15)

{

throw new Exception($"Name length {name.Length} is too long, max 15!");

}

else

{

Console.WriteLine("Hello " + name);

}

}

catch(Exception ex)

{

Console.WriteLine("Exception occurred: " + ex.Message);

}

}

Step-by-step explanation:

This is one way of doing it. More elaborate is to subclass Exception into NameLengthException and throw that.

User Ali Heikal
by
5.2k points