I have a rather basic assignment that involves using try/catch to show a number of names depending on the number entered(using an array). If the number entered is too large it may still display the names but also has to give an out of bounds error. If a word or something similar is used it needs to give a format error.
So far my code works reasonably well since it can display an out of bounds error but when I enter a word I do not get a format error.
I would also like to know if there would be a possibility to cause an error to occur if the number is lower than 5(in a situation where only 5 is accepted).
here is my code:
class Program
{
static void Main(string[] args)
{
string[] names = new string[5] { "Merry", "John", "Tim", "Matt", "Jeff" };
string read = Console.ReadLine();
int appel;
try
{
int.TryParse(read, out appel);
for (int a = 0; a < appel; a++)
{
Console.WriteLine(names[a]);
}
}
catch(FormatException e)
{
Console.WriteLine("This is a format error: {0}", e.Message);
}
catch (OverflowException e)
{
Console.WriteLine("{0}, is outside the range of 5. Error message: {1}", e.Message);
}
catch (Exception e)
{
Console.WriteLine("out of range error. error message: {0}", e.Message);
}
Console.ReadLine();
}
}
int.TryParsedoesn't throw exceptions, intead it returnstrueif conversion succeed, andfalseotherwise