0

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();
    }
}
3
  • 1
    int.TryParse doesn't throw exceptions, intead it returns true if conversion succeed, and false otherwise Commented Nov 4, 2014 at 12:37
  • You shouldn't catch all those exceptions but test your parameters before instead. Commented Nov 4, 2014 at 12:37
  • why do you want to throw and exception where a number is lower than 5? Commented Nov 4, 2014 at 13:17

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

1 Comment

That was the perfect answer, now it all makes sense again :D
0
        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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.