首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 自訂例外處理:繼承 Exception 基底類別、多載建構函式與實務範例

     編輯:關於C語言

例外處理基礎

例外為執行期錯誤,C# 透過 Exception 基底類別處理。可自訂例外類別,但必須繼承 Exception。內建例外 (如 IndexOutOfRangeException) 可直接捕捉;非內建情境需自訂。

自訂例外類別:MyException

using System;

public class MyException : Exception
{
    public string s;

    public MyException() : base() { s = null; }
    public MyException(string message) : base() { s = message; }
    public MyException(string message, Exception inner) : base(message, inner) { s = message; }

    public static void Test()
    {
        string str, msg = null;
        bool flag = false;
        char ch = ' ';
        int i = 0;
        Console.Write("請輸入字串 (少於 27 字元) - ");
        str = Console.ReadLine();
        try
        {
            ch = str[i];
            while (!flag)
            {
                if (ch == '\r') flag = true;
                else { ch = str[i]; i++; }
            }
        }
        catch (Exception) { flag = true; }
        if (i > 27)
        {
            msg = "您的輸入不能超過 27 個字元!";
            throw new MyException(msg);
        }
    }

    public static void Main()
    {
        try { Test(); }
        catch (MyException e) { Console.WriteLine(e.s); }
    }
}

設計重點

  • 三個多載建構函式對應基底類別,確保多型相容
  • 真正目的:輸入超過 27 字元時拋出自訂例外,由 Main 的 catch 區塊捕獲並顯示訊息
  • 雖類似資料驗證,但示範自訂例外拋出與捕捉流程
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved