更新 : 2007 年 11 月
TypeName |
ImplementStandardExceptionConstructors |
CheckId |
CA1032 |
カテゴリ |
Microsoft.Design |
互換性に影響する変更点 |
なし |
原因
型が System.Exception を拡張し、必要なコンストラクタのすべてを宣言していません。
規則の説明
例外型では、次のコンストラクタを実装する必要があります。
public NewException()
public NewException(string)
public NewException(string, Exception)
protected または private NewException(SerializationInfo, StreamingContext)
コンストラクタを完全に宣言していないと、例外を正しく処理するのが困難になります。たとえば、シグネチャが NewException(string, Exception) であるコンストラクタは、他の例外によって発生する例外を作成するときに使用されます。このコンストラクタがないと、内部に (入れ子になった) 例外を含むカスタムの例外のインスタンスを作成してスローすることができなくなります。これは、マネージ コードに必要な処理です。最初の 3 つの例外コンストラクタは、規約ではパブリックです。4 つ目のコンストラクタは、シールされていないクラスではプロテクトであり、シールされているクラスではプライベートです。詳細については、「シリアル化コンストラクタを実装します」を参照してください。
違反の修正方法
この規則違反を修正するには、例外に必要なコンストラクタを追加し、適切なアクセシビリティを指定します。
警告を抑制する状況
パブリック コンストラクタに異なるアクセス レベルを指定することでこの違反が発生する場合は、この規則による警告を抑制しても安全です。
使用例
この規則に違反する例外型と、適切に実装した例外型を次の例に示します。
using System;
using System.Runtime.Serialization;
namespace DesignLibrary
{
// Violates rule ImplementStandardExceptionConstructors.
public class BadException : Exception
{
public BadException()
{
// Add any type-specific logic, and supply the default message.
}
}
[Serializable()]
public class GoodException : Exception
{
public GoodException()
{
// Add any type-specific logic, and supply the default message.
}
public GoodException(string message): base(message)
{
// Add any type-specific logic.
}
public GoodException(string message, Exception innerException):
base (message, innerException)
{
// Add any type-specific logic for inner exceptions.
}
protected GoodException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
// Implement type-specific serialization constructor logic.
}
}
}