Является ли использование TimeoutException хорошей практикой? - PullRequest
0 голосов
/ 08 сентября 2018

Я определяю класс исключений для класса ввода-вывода устройства.

Я хотел бы выдать исключение, когда связь с устройством истекло. Ниже то, что у меня есть на данный момент:

    /// <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}.")
        {
        }

        /// <summary>
        /// Initializes a new instance of the <c>FanucLib.FanucTimeoutException</c> class with
        /// a specified error message and a reference to the inner exception that is the
        /// cause of this exception.
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="innerException">The exception that is the cause of the current exception. If the innerException
        /// parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception.</param>
        public FanucTimeoutException(string message, Exception innerException) : base(message, innerException)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <c>FanucLib.FanucTimeoutException</c> class with
        /// a specified error message, the address trying to access and a reference to the inner exception that is the
        /// cause of this exception.
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="address">The address trying to access.</param>
        /// <param name="innerException">The exception that is the cause of the current exception. If the innerException
        /// parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception.</param>
        public FanucTimeoutException(string message, string address, Exception innerException) : base($"{message} Address: {address}.", innerException)
        {
        }

        /// <inheritdoc />
        public FanucTimeoutException(SerializationInfo info, StreamingContext context)
        {
        }
    }

Однако я не уверен, стоит ли бросать TimeoutException. Как C # guide , так и .Net guide по разработке исключений не говорят о TimeoutException. Они только предлагают использовать несколько типов исключений, таких как InvalidOperationException и ArgumentException.

Могу ли я использовать только эти предложенные типы исключений или у меня есть свобода использования всего диапазона, кроме тех, которые рекомендованы в руководстве?

Ответы [ 2 ]

0 голосов
/ 08 сентября 2018

Лично я чувствую, что выбрасывать пользовательское исключение лучше, чем выбрасывать стандартное исключение (которое также может быть выброшено через другие области кода), и поэтому я не могу точно определить реальную проблему с исходным кодом.

Кроме того, я считаю, что следует попытаться вызвать исключение, а не возвращать коды ошибок и т. Д. (0, 1 и т. Д.) Для удобства чтения и поддержки. Это руководство содержит больше информации о лучших практиках:

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

0 голосов
/ 08 сентября 2018

Это должно быть вполне приемлемо. Я не могу представить, почему кто-то не согласится. Есть даже исключения, которые считаются «плохой практикой», которые все еще используются. Это субъективно, является ли эта практика приемлемой, но в вашей ситуации я бы сказал, что это хорошо. Любой, у кого есть опыт, может не согласиться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...