As you need to check several types of invalid input (not empty, null and only English chars), my advice is to create the custom exception with a property for invalid input type. The example is below:
class InvalidInputCustomException : Exception { public string InputExceptionType { get; set; } public InvalidInputCustomException(string inputExceptionType) { InputExceptionType = inputExceptionType; } }
Then you’ll need to create your class Man in which set accessor the input (in this code keyword value) will be checked and code lines - throw new InvalidInputCustomException .. - with corresponding input exception type in this custom exception constructor will be included. This class example is below:
class Man { private string _name; public Man(string name) { this.Name = name; } public string Name { get { return _name; } set { if (value == null) { throw new InvalidInputCustomException("null is not valid for input."); } else if (value == string.Empty) { throw new InvalidInputCustomException("empty is not valid for input."); } else { foreach (char ch in value) { if (!(ch >= 'A' && ch <= 'Z') && !(ch >= 'a' && ch <= 'z') && !(ch >= '0' && ch <= '9')) { throw new InvalidInputCustomException($"non English character {ch} is " + $"not valid for input."); ; } } } _name = value; } } }
The thrown exception must be caught in the place where to initialized Man class object its property Name is attempted to set (as for example:
p.Name = inputString
or through this object constructor as in the code example below). The example of the Console application code is below:
class Program { static void Main(string[] args) { Console.WriteLine("Enter name and press key Enter:"); string inputString = Console.ReadLine(); try { Man p = new Man(inputString); Console.WriteLine($"Entered name - {p.Name} - is valid."); } catch (InvalidInputCustomException ex) { Console.WriteLine($"Invalid input type - {ex.InputExceptionType}. Please enter valid name."); } catch (Exception ex) { Console.WriteLine("Unhandled exception " + ex.Message); } Console.WriteLine("Press any key to finish the program."); Console.ReadLine(); } }
The code example is more for custom exceptions understanding purposes. In real applications, you need to avoid exceptions throwing in situations related to user information entering - in this case, data validation tools must be used. During custom exception creation in a real application must be provided at least a parameterless constructor and a best practice is to add three additional constructors: with a string, with a string and an exception, for serialization.
ArgumentNullExceptioninstead. Also you want to checkvalue, notname.this.Namenotthis.name- otherwise you don't use the setter method. Also you should not catch an exception and create the same new. you can use justthrow;to throw the same exception more up (you will see in log).