C#中的用户定义异常
C#用户定义的异常
在C#中,我们可以通过继承基类Exception来创建异常类。因为我们知道Exception是C#中所有类型的异常的基类。
这是用户定义的异常的示例,
using System;
class UserDefineException: Exception
{
public UserDefineException(string str)
{
Console.WriteLine(str);
}
}
class Program
{
static void Main()
{
UserDefineException M = new UserDefineException("User Define Exception");
try
{
throw M;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}输出结果
User Define Exception Exception of type 'UserDefineException' was thrown.
在上述程序中,我们通过继承基类“Exception”创建了一个“UserDefineException”类,并通过“Program”类的“try块”中的用户定义对象创建了一个参数化构造函数,将其捕获在“catch块”中“。
阅读更多:
C#中的异常处理
具有多个catch块的C#异常处理