I am new to this forum and also programming only in my second week at uni so thanks in advance for your help and pateince

It is only a simple program and i am trying to confirm the reason for this error ( pasted at the bottom)
I assume it is due to the incorrect format of the string.
All i am trying to achieve is validation of user input when/if invalid year was entered.
If letters are entered it crashes the program and generates the error.
And if an incorrect year is entered it will only allow the user to enter a year 1 more time, and if that is incorrect it will not repeat until correct year is entered.

Any help would be greatly appreciated.

Thanks

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Prac1._1
{
    class Program
    {
        static void Main(string[] args)
        {
            int Year;
            string Title;
            string Publisher;
            int Length ;
            bool repeat = true;

            while (repeat == true)
            {
                Console.WriteLine("\nMovie Information! Press 'enter' to continue...");

                Console.ReadLine();

                Console.Write("Input Movie Title: ");
                Title = Console.ReadLine();
                Console.WriteLine("Movie Title: {0} ", Title);



                {
                    Console.WriteLine("\nInput Year Released: ");
                    string input = Console.ReadLine();

                    Year = Int32.Parse(input); // Format Exception was unhandled (appears on this line)

                    if (Year < 1886 || Year > 2012)

                    {
                        Console.WriteLine("No movies were made before 1886 or after 2011. Please try again.");
                        Console.WriteLine("\nInput Year Released: ");
                        Console.ReadLine();
                    }

                    else

                    {
                        Console.WriteLine("Year Released: {0} ", Year);
                    }
                }

                Console.Write("\nInput Publisher: ");
                Publisher = Console.ReadLine();
                Console.WriteLine("Publisher: {0} ", Publisher);

                Console.Write("\nInput Length (hrs): ");
                Length = Convert.ToInt32(null); Console.ReadLine();
                Console.WriteLine("Length (hrs): {0} ", Length);

                Console.WriteLine("Go again? Y/N");

                string go = Console.ReadLine();
                if (go == "Y" || go == "y")
                {
                    repeat = true;
                }
                else
                {
                    repeat = false;

                    Console.WriteLine("Press any key to exit.");
                   
                }
            }



            
        }
    }
}

Error:

System.FormatException was unhandled
Message=Input string was not in a correct format.
Source=mscorlib
StackTrace:
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.Int32.Parse(String s)
at Prac1._1.Program.Main(String[] args) in \\vmware-host\Shared Folders\Desktop\Visual Projects\Prac1.1\Prac1.1\Program.cs:line 35
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

Recommended Answers

All 3 Replies

Hi,
This line
Year = Int32.Parse(input);
is crashing because you are trying to parse letters (non-numeric characters) into an integer. This isn't going to work. A string would have to contain only the digits 0-9 (any number of them) to be parsed to a integer.
Your simplest solution is to wrap that section in a try/catch block where the exception triggers a console message prompting the user to try again. Or first check the string only contains numbers before calling the parse command.

On an aside, you have given your variables captialised names e.g. int Year. Classes generally have uppercase names while variables are lower case (int year). This is an expected convention across most languages and you should follow it. If someone else was to read part of your code and saw Year, they would expect that to be a class.

Hope that helps,

Your simplest solution is to wrap that section in a try/catch block where the exception triggers a console message prompting the user to try again. Or first check the string only contains numbers before calling the parse command.

I disagree, the simplest solution is to use Int32.TryParse(). Using exceptions for validation slows your code and is generally poor design.

commented: Yes! +15

Hericles,

Thanks for the help, very informative i will put it in a try/catch block and let you know how it goes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.