次の方法で共有


CA1064: 例外は public として設定する必要があります

TypeName

ExceptionsShouldBePublic

CheckId

CA1064

[カテゴリ]

Microsoft.Design

互換性に影響する変更点

なし

原因

パブリックでない例外が ExceptionSystemException または ApplicationException から直接派生しています。

規則の説明

内部例外は、その内部スコープ内でのみ認識されます。内部スコープの外側にある例外は、基本例外を使用しなければキャッチできません。内部例外が ExceptionSystemException、または ApplicationException を継承している場合、外部コードはその例外の処理に関する十分な情報を取得できません。

しかし、外部コードに後で内部例外の基本例外として使用できるパブリック例外があれば、それ以降に基本例外を使用して高度な処理を実行できると考えることは理にかなっています。パブリック例外は、T:System.Exception、T:System.SystemException、または T:System.ApplicationException が提供するより多くの情報を保持します。

違反の修正方法

例外をパブリックにするか、ExceptionSystemException、または ApplicationException 以外のパブリック例外から内部例外を派生させます。

警告を抑制する状況

プライベート例外がその内部スコープ内でキャッチされることが確実である場合は、この規則によるメッセージを抑制してください。

使用例

最初のメソッド例 FirstCustomException では、この例外クラスが直接 Exception から派生する内部的な例外のため、この規則が適用されます。SecondCustomException クラスは、同様に直接 Exception から派生しますが、パブリックとして宣言されているため、この規則は適用されません。3 番目のクラスも、System.ExceptionSystem.SystemException、または System.ApplicationException から直接派生していないため、この規則は適用されません。

using System;
using System.Runtime.Serialization;

namespace Samples
{
    // Violates this rule
    [Serializable]
    internal class FirstCustomException : Exception
    {
        internal FirstCustomException()
        {
        }

        internal FirstCustomException(string message)
            : base(message)
        {
        }

        internal FirstCustomException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

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

    // Does not violate this rule because
    // SecondCustomException is public
    [Serializable]
    public class SecondCustomException : Exception
    {
        public SecondCustomException()
        {
        }

        public SecondCustomException(string message)
            : base(message)
        {

        }

        public SecondCustomException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

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

    // Does not violate this rule because
    // ThirdCustomException it does not derive directly from
    // Exception, SystemException, or ApplicationException
    [Serializable]
    internal class ThirdCustomException : SecondCustomException
    {
        internal ThirdCustomException()
        {
        }

        internal ThirdCustomException(string message)
            : base(message)
        {
        }

        internal ThirdCustomException(string message, Exception innerException)
            : base(message, innerException)
        {
        }


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