溫馨提示×

C#中Throw如何處理自定義異常

c#
小樊
92
2024-07-30 14:23:10
欄目: 編程語言

在C#中,可以通過自定義異常類來創(chuàng)建自定義的異常。首先需要定義一個(gè)自定義異常類,通常繼承自Exception類。然后,在代碼中通過throw關(guān)鍵字拋出自定義異常。

下面是一個(gè)簡單的例子:

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類,并重寫了構(gòu)造函數(shù)。然后在Main方法中,通過throw關(guān)鍵字拋出自定義異常CustomException。在catch塊中捕獲CustomException并輸出異常信息。如果拋出的異常不是CustomException,會(huì)被捕獲到通用的Exception塊中。

0