C#教程
C#控制语句
C#函数
C#数组
C#面向对象
C#命名空间和异常
C#文件IO
C#集合
C#多线程
C#其它

C# 自定义异常

C# 用户定义异常

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

C#用户自定义异常示例

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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4