c#

C#中Throw如何处理自定义异常

小樊
92
2024-07-30 14:23:10
栏目: 编程语言

在C#中,可以通过自定义异常类来创建自定义的异常。首先需要定义一个自定义异常类,通常继承自Exception类。然后,在代码中通过throw关键字抛出自定义异常。

下面是一个简单的例子:

using System;

public class CustomException : Exception
{
    public CustomException(string message) : base(message)
    {
    }
}

public class Program
{
    public static void Main()
    {
        try
        {
            throw new CustomException("This is a custom exception.");
        }
        catch (CustomException ex)
        {
            Console.WriteLine("Custom Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("General Exception: " + ex.Message);
        }
    }
}

在上面的例子中,CustomException类继承自Exception类,并重写了构造函数。然后在Main方法中,通过throw关键字抛出自定义异常CustomException。在catch块中捕获CustomException并输出异常信息。如果抛出的异常不是CustomException,会被捕获到通用的Exception块中。

0
看了该问题的人还看了