Answers for "c# creating exceptions"

C#
1

c# creating exceptions

class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
}

[Serializable]
class InvalidStudentNameException : Exception
{
    public InvalidStudentNameException()
    {

    }

    public InvalidStudentNameException(string name)
        : base(String.Format("Invalid Student Name: {0}", name))
    {

    }
  
}


class Program
{
    static void Main(string[] args)
    {
        Student newStudent = null;
          
        try
        {               
            newStudent = new Student();
            newStudent.StudentName = "James007";
            
            ValidateStudent(newStudent);
        }
        catch(InvalidStudentNameException ex)
        {
            Console.WriteLine(ex.Message );
        }
          

        Console.ReadKey();
    }

    private static void ValidateStudent(Student std)
    {
        Regex regex = new Regex("^[a-zA-Z]+$");

        if (!regex.IsMatch(std.StudentName))
             throw new InvalidStudentNameException(std.StudentName);
            
    }
}
Posted by: Guest on April-27-2020

C# Answers by Framework

Browse Popular Code Answers by Language