Condividi tramite


CA2208: Creare istanze di eccezioni di argomento correttamente

TypeName

InstantiateArgumentExceptionsCorrectly

CheckId

CA2208

Category

Microsoft.Usage

Breaking Change

Non sostanziale

Causa

Fra le possibili cause sono incluse le seguenti situazioni:

  • Viene effettuata una chiamata al costruttore predefinito (senza parametri) di un tipo di eccezione che è o deriva da [System.ArgumentException].

  • Un argomento di stringa non corretto viene passato a un costruttore con parametri di un tipo di eccezione che è o che deriva da [System.ArgumentException.]

Descrizione della regola

Anziché chiamare il costruttore predefinito, chiamare uno degli overload del costruttore che consenta di fornire un messaggio di eccezione più significativo. Il messaggio di eccezione deve essere rivolto allo sviluppatore e spiegare chiaramente la condizione di errore e come correggere o evitare l'eccezione.

Le firme dei primi due costruttori di stringa di ArgumentException e i relativi tipi derivati non sono coerenti con i parametri message e paramName. Accertarsi che questi costruttori siano chiamati con gli argomenti stringa corretti. Le firme sono le seguenti:

ArgumentException(string message)

ArgumentException(string message, string paramName)

ArgumentNullException(string paramName)

ArgumentNullException(string paramName, string message)

ArgumentOutOfRangeException(string paramName)

ArgumentOutOfRangeException(string paramName, string message)

DuplicateWaitObjectException(string parameterName)

DuplicateWaitObjectException(string parameterName, string message)

Come correggere le violazioni

Per correggere una violazione di questa regola, chiamare un costruttore che accetta un messaggio, un nome di parametro o entrambi e assicurarsi che gli argomenti siano adatti al tipo di ArgumentException da chiamare.

Esclusione di avvisi

L'esclusione di un avviso da questa regola è sicura solo se un costruttore con parametri viene chiamato con gli argomenti stringa corretti.

Esempio

Nell'esempio riportato di seguito viene illustrato un costruttore che crea in modo errato un'istanza di un'istanza del tipo ArgumentNullException.

Imports System

Namespace Samples1

    Public Class Book

        Private ReadOnly _Title As String

        Public Sub New(ByVal title As String)
            ' Violates this rule (constructor arguments are switched)            
            If (title Is Nothing) Then
                Throw New ArgumentNullException("title cannot be a null reference (Nothing in Visual Basic)", "title")
            End If
            _Title = title
        End Sub

        Public ReadOnly Property Title()
            Get
                Return _Title
            End Get
        End Property

    End Class

End Namespace
using System;

namespace Samples1
{    
    public class Book    
    {        
        private readonly string _Title;

        public Book(string title)        
        {            
            // Violates this rule (constructor arguments are switched)            
            if (title == null)                
                throw new ArgumentNullException("title cannot be a null reference (Nothing in Visual Basic)", "title");

            _Title = title;        
        }

        public string Title        
        {            
            get { return _Title; }        
        }
    }
}
using namespace System;

namespace Samples1 
{    
    public ref class Book    
    {
     private: initonly String^ _Title;

    public:
        Book(String^ title)        
        {            
            // Violates this rule (constructor arguments are switched)            
            if (title == nullptr)                
                throw gcnew ArgumentNullException("title cannot be a null reference (Nothing in Visual Basic)", "title");

            _Title = title;        
        }

        property String^ Title        
        {            
            String^ get()            
            {                
                return _Title;            
            }        
        }    
    };
}

Nell'esempio riportato di seguito viene risolta la violazione suddetta scambiando gli argomenti del costruttore.

Namespace Samples2

    Public Class Book

        Private ReadOnly _Title As String

        Public Sub New(ByVal title As String)
            If (title Is Nothing) Then
                Throw New ArgumentNullException("title", "title cannot be a null reference (Nothing in Visual Basic)")
            End If

            _Title = title
        End Sub

        Public ReadOnly Property Title()
            Get
                Return _Title
            End Get
        End Property

    End Class

End Namespace
namespace Samples2
{    
    public class Book    
    {        
        private readonly string _Title;

        public Book(string title)        
        {            
            if (title == null)                
                throw new ArgumentNullException("title", "title cannot be a null reference (Nothing in Visual Basic)");

            _Title = title;        }

        public string Title        
        {            
            get { return _Title; }        
        }
    }
}
using namespace System;

namespace Samples2 
{    
    public ref class Book    
    {
     private: initonly String^ _Title;

    public:
        Book(String^ title)        
        {            
            if (title == nullptr)                
                throw gcnew ArgumentNullException(("title", "title cannot be a null reference (Nothing in Visual Basic)"));

            _Title = title;        
        }

        property String^ Title        
        {            
            String^ get()            
            {                
                return _Title;            
            }        
        }    
    };
}