Question

I want to catch the exceptions when the end user types invalid format or left the field without entering any data.I used string type for first Name and Last Name.Here is the problem since the string type accepts both string type data and numeric data catch block is not able to catch the exceptions for invalid data entry.Also since string type default value is null, not able to catch the exception when field is left empty.

For example, I want to catch the exception when user types 123 in the fname field or left the field without entering data.

     static void Main(string[] args)
    {
        string fName = null;
        string lName = null;

        try
        {             

            Console.Write("Enter your first Name  ");
            fName = Console.ReadLine();

            Console.Write("Enter your Last Name  ");
            lName = Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine("Please enter correct format");
        }

     }
Était-ce utile?

La solution

You don't really need a try-catch block. Since you have captured the fields in your local variables then you can perform the validation on them.

if (String.IsNullOrEmpty(fName)) {
  // handle empty string input
}

if (ContainsNumbers(fName)) {
  // handle invalid input
}

private bool ContainsNumbers(string str) {
  ...
}

Autres conseils

"123" is as much a valid string as is "abc". What you want to to is check if what the user entered only contains word characters. You would do that like so:

Regex regex = new Regex("(\w+)");
fname = Console.ReadLine();
if (!regex.Match(fname).Success)
{
    // throw exception here, as the entered value did not contain word characters.
}

You need to validate the entries manually and then throw an exception.

BUT... you really should not use Exceptions for data validation, an Exception is used when something NOT expected has occurred.... like network errors, db errors, etc...

For data validations a simple IF statement is enough.

Hope it helps.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top