Reputation: 15
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();
}
}
Upvotes: 0
Views: 169
Reputation: 1649
bool b = int.TryParse(read, out appel);
if(!b)
throw new FormatException("{0} is not a valid argument", read);
or
int.Parse(read, out appel);
which will throw a formatexception whenever the wrong value is entered.
Upvotes: 0
Reputation: 21795
int.TryParse(read, out appel);
This code will not throw any exception, this will either return True(if parsing succeeds else false). If you intend to throw an exception use: int.Parse
Upvotes: 1