ArgumentException Klasa

Definicja

Wyjątek zgłaszany, gdy jeden z argumentów dostarczonych do metody jest nieprawidłowy.

public ref class ArgumentException : Exception
public ref class ArgumentException : SystemException
public class ArgumentException : Exception
public class ArgumentException : SystemException
[System.Serializable]
public class ArgumentException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ArgumentException : SystemException
type ArgumentException = class
    inherit Exception
type ArgumentException = class
    inherit SystemException
type ArgumentException = class
    inherit SystemException
    interface ISerializable
[<System.Serializable>]
type ArgumentException = class
    inherit SystemException
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ArgumentException = class
    inherit SystemException
    interface ISerializable
Public Class ArgumentException
Inherits Exception
Public Class ArgumentException
Inherits SystemException
Dziedziczenie
ArgumentException
Dziedziczenie
ArgumentException
Pochodne
Atrybuty
Implementuje

Przykłady

W poniższym przykładzie pokazano, jak zgłaszać i przechwytywać element ArgumentException. Używa ona argumentu ArgumentException.GetType(). Właściwość Name do wyświetlania nazwy obiektu wyjątku, a także używa Message właściwości do wyświetlania tekstu komunikatu wyjątku.

using namespace System;

static int DivideByTwo(int num) 
{
    // If num is an odd number, throw an ArgumentException.
    if ((num & 1) == 1)
        throw gcnew ArgumentException(String::Format("{0} is not an even number", num), 
                                      "num");

    // num is even, return half of its value.
    return num / 2;
}

void main() 
{
    // Define some integers for a division operation.
    array<int>^ values = { 10, 7 };
    for each (int value in values) {
        try {
           Console::WriteLine("{0} divided by 2 is {1}", value, DivideByTwo(value));
        }
        catch (ArgumentException^ e) {
           Console::WriteLine("{0}: {1}", e->GetType()->Name, e->Message);
        }
        Console::WriteLine();
    }
}
// This example displays the following output:
//     10 divided by 2 is 5
//     
//     ArgumentException: 7 is not an even number
//     Parameter name: num
using System;

public class Example
{
    static void Main()
    {
        // Define some integers for a division operation.
        int[] values = { 10, 7 };
        foreach (var value in values) {
            try {
               Console.WriteLine("{0} divided by 2 is {1}", value, DivideByTwo(value));
            }
            catch (ArgumentException e) {
               Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
            }
            Console.WriteLine();
        }
    }

    static int DivideByTwo(int num)
    {
        // If num is an odd number, throw an ArgumentException.
        if ((num & 1) == 1)
            throw new ArgumentException(String.Format("{0} is not an even number", num),
                                      "num");

        // num is even, return half of its value.
        return num / 2;
    }
}
// This example displays the following output:
//     10 divided by 2 is 5
//
//     ArgumentException: 7 is not an even number
//     Parameter name: num
open System

let divideByTwo num =
    // If num is an odd number, throw an ArgumentException.
    if num % 2 = 1 then
        invalidArg "num" $"{num} is not an even number"

    // num is even, return half of its value.
    num / 2;

// Define some integers for a division operation.
let values = [ 10; 7 ]
for value in values do
    try 
        printfn $"{value} divided by 2 is {divideByTwo value}"
    with
    | :? ArgumentException as e ->
        printfn $"{e.GetType().Name}: {e.Message}"
    
    printfn ""

// This example displays the following output:
//     10 divided by 2 is 5
//
//     ArgumentException: 7 is not an even number (Parameter 'num')
Public Class Example
    Public Shared Sub Main()
        ' Define some integers for a division operation.
        Dim values() As Integer = { 10, 7 }

        For Each value In values
            Try 
               Console.WriteLine("{0} divided by 2 is {1}", value, DivideByTwo(value))
            Catch e As ArgumentException
               Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message)
            End Try
            Console.WriteLine()
        Next
    End Sub
    
    Private Shared Function DivideByTwo(ByVal num As Integer) As Integer
        ' If num is an odd number, throw an ArgumentException.
        If (num And 1) = 1 Then
            Throw New ArgumentException(String.Format("{0} is not an even number", num), 
                                      "num")
        End If
        Return num \ 2
    End Function
End Class
' The example displays the following output:
'     10 divided by 2 is 5
'     
'     ArgumentException: 7 is not an even number
'     Parameter name: num

Uwagi

ArgumentException jest zgłaszany, gdy wywoływana jest metoda, a co najmniej jeden z przekazanych argumentów nie spełnia specyfikacji parametru wywoływanej metody. Właściwość ParamName identyfikuje nieprawidłowy argument.

ArgumentException Najczęściej element jest zgłaszany przez środowisko uruchomieniowe języka wspólnego lub inną bibliotekę klas i wskazuje błąd dewelopera. Jeśli wyrzucisz element ArgumentException z kodu, upewnij się, że właściwość wyjątku Message zawiera znaczący komunikat o błędzie opisujący nieprawidłowy argument i oczekiwany zakres wartości argumentu.

Podstawowe klasy ArgumentException pochodne klasy to ArgumentNullException i ArgumentOutOfRangeException. Te klasy pochodne powinny być używane zamiast ArgumentException, z wyjątkiem sytuacji, w których żadna z klas pochodnych nie jest akceptowalna. Na przykład wyjątki powinny być zgłaszane przez:

  • ArgumentNullException za każdym razem, gdy null jest przekazywana do metody, która nie akceptuje jej jako prawidłowego argumentu.

  • ArgumentOutOfRangeException gdy wartość argumentu znajduje się poza zakresem dopuszczalnych wartości; na przykład gdy wartość "46" jest przekazywana jako argument miesiąca podczas tworzenia elementu DateTime.

Jeśli wywołanie metody nie ma żadnego argumentu lub jeśli błąd nie obejmuje samych argumentów, należy go InvalidOperationException użyć.

ArgumentException używa COR_E_ARGUMENT HRESULT, która ma wartość 0x80070057.

Aby uzyskać listę początkowych wartości właściwości dla wystąpienia ArgumentExceptionklasy , zobacz ArgumentException konstruktory.

W języku F# możesz użyć funkcji invalidArg , aby wygenerować i zgłosić wyjątek ArgumentException.

Konstruktory

ArgumentException()

Inicjuje nowe wystąpienie klasy ArgumentException.

ArgumentException(SerializationInfo, StreamingContext)
Przestarzałe.

Inicjuje nowe wystąpienie klasy ArgumentException z zserializowanymi danymi.

ArgumentException(String)

Inicjuje ArgumentException nowe wystąpienie klasy z określonym komunikatem o błędzie.

ArgumentException(String, Exception)

Inicjuje nowe wystąpienie ArgumentException klasy z określonym komunikatem o błędzie i odwołaniem do wyjątku wewnętrznego, który jest przyczyną tego wyjątku.

ArgumentException(String, String)

Inicjuje nowe wystąpienie ArgumentException klasy z określonym komunikatem o błędzie i nazwą parametru, który powoduje ten wyjątek.

ArgumentException(String, String, Exception)

Inicjuje nowe wystąpienie ArgumentException klasy z określonym komunikatem o błędzie, nazwą parametru i odwołaniem do wewnętrznego wyjątku, który jest przyczyną tego wyjątku.

Właściwości

Data

Pobiera kolekcję par klucz/wartość, które zapewniają dodatkowe informacje zdefiniowane przez użytkownika dotyczące wyjątku.

(Odziedziczone po Exception)
HelpLink

Pobiera lub ustawia link do pliku pomocy skojarzonego z tym wyjątkiem.

(Odziedziczone po Exception)
HResult

Pobiera lub ustawia HRESULT, zakodowaną wartość liczbową przypisaną do określonego wyjątku.

(Odziedziczone po Exception)
InnerException

Exception Pobiera wystąpienie, które spowodowało bieżący wyjątek.

(Odziedziczone po Exception)
Message

Pobiera komunikat o błędzie i nazwę parametru lub tylko komunikat o błędzie, jeśli nie ustawiono nazwy parametru.

ParamName

Pobiera nazwę parametru, który powoduje ten wyjątek.

Source

Pobiera lub ustawia nazwę aplikacji lub obiektu, który powoduje błąd.

(Odziedziczone po Exception)
StackTrace

Pobiera reprezentację ciągu natychmiastowych ramek na stosie wywołań.

(Odziedziczone po Exception)
TargetSite

Pobiera metodę, która zgłasza bieżący wyjątek.

(Odziedziczone po Exception)

Metody

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetBaseException()

Po przesłonięciu w klasie pochodnej funkcja zwraca Exception główną przyczynę co najmniej jednego kolejnego wyjątku.

(Odziedziczone po Exception)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetObjectData(SerializationInfo, StreamingContext)
Przestarzałe.

SerializationInfo Ustawia obiekt z nazwą parametru i dodatkowymi informacjami o wyjątku.

GetObjectData(SerializationInfo, StreamingContext)
Przestarzałe.

Po zastąpieniu w klasie pochodnej ustawia SerializationInfo element z informacjami o wyjątku.

(Odziedziczone po Exception)
GetType()

Pobiera typ środowiska uruchomieniowego bieżącego wystąpienia.

(Odziedziczone po Exception)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ThrowIfNullOrEmpty(String, String)

Zgłasza wyjątek, jeśli argument jest null lub jest pusty.

ThrowIfNullOrWhiteSpace(String, String)

Zgłasza wyjątek, jeśli argument jest null, pusty lub składa się tylko z białych znaków.

ToString()

Tworzy i zwraca reprezentację ciągu bieżącego wyjątku.

(Odziedziczone po Exception)

Zdarzenia

SerializeObjectState
Przestarzałe.

Występuje, gdy wyjątek jest serializowany w celu utworzenia obiektu stanu wyjątku, który zawiera serializowane dane dotyczące wyjątku.

(Odziedziczone po Exception)

Dotyczy

Zobacz też