C# 属性

C# 抽象

C# 字符串

C# 泛型

C# 杂项

C# 新特性

C# User-Defined Exceptions 用户定义的异常

C# 允许我们创建用户定义的或自定义的异常。它用于产生有意义的异常。为此,我们需要继承 Exception 类。

C# 用户定义异常示例

例子 (Example)

using System;  
public class InvalidAgeException : Exception  
{  
    public InvalidAgeException(String message)  
        : base(message)  
    {  
  
    }  
}  
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


  • 使用社交账号登录,本站支持
全部评论(0)