C# 自定义异常类型

C# 包含很多内置异常类型,例如 NullReferenceException、MemoryOverflowException 等。 但是,很多时候有一些数据不符合我们的业务规则的时候,我们需要自定义这个异常。 我们可以通过继承 Exception 类来创建自定义异常类。

例如,在学校应用程序中创建 InvalidStudentNameException 类,该类表示学生的姓名中不能包含任何特殊字符或数字值。

public class Student
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class InvalidStudentNameException : Exception
{
    public InvalidStudentNameException()
    {

    }

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

    }

}

现在,只要名称包含特殊字符或数字,我们就可以在程序中通过 throw 关键字抛出 InvalidStudentNameException。

class Program
{
    static void Main(string[] args)
    {
        Student newStudent = null;

        try
        {
            newStudent = new Student();
            newStudent.Name = "James007";

            ValidateStudent(newStudent);
        }
        catch (InvalidStudentNameException ex)
        {
            Console.WriteLine(ex.Message);//输出 Invalid Student Name: James000
        }


        Console.ReadKey();
    }

    private static void ValidateStudent(Student std)
    {
        //正则表达式需要 using System.Text.RegularExpressions;
        var regex = new Regex("^[a-zA-Z]+$");

        if (!regex.IsMatch(std.Name))
            throw new InvalidStudentNameException(std.Name);

    }
}
下一篇:C# 委托
最近更新的
...