亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

拋出 TimeoutException 是一個好習慣嗎?

拋出 TimeoutException 是一個好習慣嗎?

C#
素胚勾勒不出你 2022-01-09 10:42:44
我正在為設備 IO 類定義一個異常類。當與設備的通信超時時,我想拋出一個異常。以下是我目前擁有的:    /// <summary>    /// The exception that is thrown when the time allotted for talking to the FANUC controller has expired.    /// </summary>    [Serializable]    public class FanucTimeoutException : TimeoutException    {        /// <summary>        /// Initializes a new instance of the <c>FanucLib.FanucTimeoutException</c> class.        /// </summary>        public FanucTimeoutException() { }        /// <summary>        /// Initializes a new instance of the <c>FanucLib.FanucTimeoutException</c> class with the specified error message.        /// </summary>        /// <param name="message">The message that describes the error. </param>        public FanucTimeoutException(string message) : base(message)        {        }        /// <summary>        /// Initializes a new instance of the <c>FanucLib.FanucTimeoutException</c> class with the specified error message and the address trying to access.        /// </summary>        /// <param name="message">The message that describes the error. </param>        /// <param name="address">The address trying to access.</param>        public FanucTimeoutException(string message, string address) : base($"{message} Address: {address}.")        {        }        public FanucTimeoutException(string message, Exception innerException) : base(message, innerException)        {        }        public FanucTimeoutException(string message, string address, Exception innerException) : base($"{message} Address: {address}.", innerException)        {        }        /// <inheritdoc />        public FanucTimeoutException(SerializationInfo info, StreamingContext context)        {        }    }但是,我不確定 throw 是否是一個好習慣TimeoutException。無論C#教程和凈指導對例外的設計不談TimeoutException。他們只建議使用少數異常類型,例如InvalidOperationException和ArgumentException。我是否僅限于使用這些建議的異常類型,或者我是否可以自由使用除指南中建議的異常類型之外的全部范圍?
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

這應該是完全可以接受的。我無法想象為什么有人會不同意。甚至還有一些被認為是“不良做法”的例外仍然有其用途。這種做法是否可以接受是主觀的,但在你的情況下,我會說這很好。任何有更多經驗的人都可以不同意。


查看完整回答
反對 回復 2022-01-09
?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

我個人覺得拋出自定義異常比拋出標準異常(也可以通過代碼中的其他區域拋出)更好,因此無法查明實際的源代碼問題。

此外,出于可讀性和可維護性的目的,我覺得應該嘗試拋出異常而不是返回錯誤代碼等(0、1 等)。本指南提供了有關最佳實踐的更多信息:

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions


查看完整回答
反對 回復 2022-01-09
  • 2 回答
  • 0 關注
  • 194 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號