[C#.NET] 使用自訂例外 Exception

  • 12710
  • 0
  • C#
  • 2016-01-21

[C#.NET] 使用自訂例外 Exception

在多數情況下,BCL 預設的 Exception 就夠用了,但有時候我們還是必須要自訂 Exception,若需要自訂 Exception,我們可以參考 MSDN 的建議

設計自訂例外狀況

 

在 VS 裡面有 IntelliSense,輸入 ex 就會跳出 IntelliSense 提示選單,如下圖

image

 

選擇 Exception 後按下 Tab  鍵,就會自動產生以下片斷程式碼

image

 

假設要自訂 Message 格式,可以複寫 Message 方法

{
    get
    {
        if (this.Code == null)
        {
            return base.Message;
        }
        else
        {
            return string.Format("Code:{0}, Message:{1}", this.Code, base.Message);
        }
    }
}

 

效果看起來如下圖:

image


完整的程式碼看起來就像這樣

public class ModbusException : Exception
{
    public virtual byte? Code { get; set; }

    public ModbusException()
    {
    }

    public ModbusException(string message, byte? Code)
        : base(message)
    {
        this.Code = Code;
    }

    public ModbusException(string message)
        : base(message)
    {
    }

    public ModbusException(string message, Exception inner)
        : base(message, inner)
    {
    }

    protected ModbusException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }

    public override string Message
    {
        get
        {
            if (this.Code == null)
            {
                return base.Message;
            }
            else
            {
                return string.Format("Code:{0}, Message:{1}", this.Code, base.Message);
            }
        }
    }
}

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo