无涯教程-C# - 自定义异常

52 阅读1分钟

C#允许无涯教程创建用户定义的或自定义的异常。它用于生成有意义的异常。为此,需要继承异常类。

C#用户定义的异常示例

using System;  
public class InvalidAgeException : Exception  
{  
    public InvalidAgeException(String message)  
        : base(message)  
    {  
</span><span class="pun">}</span><span class="pln">  

}
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be greater than 18");
}
}
public static void Main(string[] args)
{
try
{
validate
(12);
}
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}

输出:

InvalidAgeException: Sorry, Age must be greater than 18
Rest of the code

参考链接

www.learnfk.com/csharp/c-sh…