0

I'm getting below exception while trying to print the last element in an array.

here is my code:

int[] nums = { 1, 2, 5, 7, 8 };

Console.WriteLine("first element is " + nums[0]);
int fe = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Last element is {0}" , nums[nums.Length - 1]);
int le = Convert.ToInt32(Console.ReadLine());

Exception:

first element is 1

Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at W2Resource.BasicExProb51.Main() in C:\Users\SudhaPraveen\Documents\Visual Studio 2017\Projects\CSharpPractice21DaysPlan\W2Resource\BasicExProb51.cs:line 16 Press any key to continue . . .

6
  • Debug and see what is returned by Console.ReadLine(). Commented Dec 31, 2018 at 16:27
  • 3
    Hint: the exception is not happening when you think it does. Commented Dec 31, 2018 at 16:28
  • 2
    What is your input for Console.ReadLine ? Commented Dec 31, 2018 at 16:28
  • 1
    Look at your stacktrace, you find the method which caused the exception there, it starts with at.... Compare with the methods that you use and then you know that Convert.ToInt32 threw that exception. Why? Because what was in the console was not a valid integer Commented Dec 31, 2018 at 16:29
  • Console.ReadLine() is not an integer which is why it is throwing an exception Commented Dec 31, 2018 at 16:40

1 Answer 1

2

Your lines :

Console.WriteLine("first element is " + nums[0]);
Console.WriteLine("Last element is {0}" , nums[nums.Length - 1]);

Are both correct.

Your exception comes from user input in

Convert.ToInt32(Console.ReadLine());

As long as your user type a value that can be parsed as an integer, it works. Else it will raise the kind of exception you have seen.

If you don't use the input value, you could just replace it by :

Console.ReadKey();

It will make the program to "pause" until the user press a random key of the keyboard.

Else, if you need to use it, you have to validate the input before to use it. For example, I suggest you to check the behavior and usage of the int.TryParse() method.

Here's one answer to a question similar to yours : https://stackoverflow.com/a/45259920/461444 But it uses int.Parse() instead of int.TryParse() as suggested, which is not as good because it requires more code and raise a useless and perfectly avoidable exception.

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

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.