ArgumentOutOfRangeException クラス

定義

引数の値が、呼び出されたメソッドで定義されている許容範囲外である場合にスローされる例外。

public ref class ArgumentOutOfRangeException : ArgumentException
public class ArgumentOutOfRangeException : ArgumentException
[System.Serializable]
public class ArgumentOutOfRangeException : ArgumentException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ArgumentOutOfRangeException : ArgumentException
type ArgumentOutOfRangeException = class
    inherit ArgumentException
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
[<System.Serializable>]
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
Public Class ArgumentOutOfRangeException
Inherits ArgumentException
継承
ArgumentOutOfRangeException
継承
ArgumentOutOfRangeException
属性
実装

次の例では、招待されたゲストに関する情報を含むクラスを定義します。 ゲストが 21 未満の場合は、 ArgumentOutOfRangeException 例外がスローされます。

using System;
using static System.Console;

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            var guest1 = new Guest("Ben", "Miller", 17);
            WriteLine(guest1.GuestInfo);
        }
        catch (ArgumentOutOfRangeException argumentOutOfRangeException)
        {
            WriteLine($"Error: {argumentOutOfRangeException.Message}");
        }
    }
}

class Guest
{
    private const int minimumRequiredAge = 21;

    private string firstName;
    private string lastName;
    private int age;

    public Guest(string firstName, string lastName, int age)
    {
        if (age < minimumRequiredAge)
            throw new ArgumentOutOfRangeException(nameof(age), $"All guests must be {minimumRequiredAge}-years-old or older.");

        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public string GuestInfo => $"{firstName} {lastName}, {age}";
}
open System

type Guest(fName: string, lName: string, age: int) =
    let minimumRequiredAge = 21

    do if age < minimumRequiredAge then 
        raise (ArgumentOutOfRangeException(nameof age, $"All guests must be {minimumRequiredAge}-years-old or older."))

    member _.FirstName = fName
    member _.LastName = lName
    member _.GuestInfo() = $"{fName} {lName}, {age}"

try
    let guest1 = Guest("Ben", "Miller", 17);
    printfn $"{guest1.GuestInfo()}"
with
| :? ArgumentOutOfRangeException as e ->
    printfn $"Error: {e.Message}"
Module Module1
   Public Sub Main()
       Try
           Dim guest1 As Guest = New Guest("Ben", "Miller", 17)
           Console.WriteLine(guest1.GuestInfo)
       Catch outOfRange As ArgumentOutOfRangeException
           Console.WriteLine("Error: {0}", outOfRange.Message)
       End Try
   End Sub
End Module

Class Guest
    Private FirstName As String
    Private LastName As String
    Private Age As Integer

    Public Sub New(ByVal fName As String, ByVal lName As String, ByVal age As Integer)
        MyBase.New()
        FirstName = fName
        LastName = lName
        If (age < 21) Then
            Throw New ArgumentOutOfRangeException("age", "All guests must be 21-years-old or older.")
        Else
            age = age
        End If
    End Sub

    Public Function GuestInfo() As String
        Dim gInfo As String = (FirstName + (" " _
                    + (Me.LastName + (", " + Me.Age.ToString))))
        Return gInfo
    End Function
End Class

注釈

ArgumentOutOfRangeExceptionメソッドが呼び出され、メソッドに渡される引数の少なくとも 1 つがではなくnull、引数に必要な値のセットのメンバーではない無効な値が含まれている場合、例外がスローされます。 プロパティは ParamName 無効な引数を識別し ActualValue 、値が存在する場合は無効な値を識別します。

通常、開発者エラーが ArgumentOutOfRangeException 発生します。 例外をブロックで try/catch 処理する代わりに、例外の原因を排除する必要があります。または、例外をスローするメソッドに渡される前に、メソッド呼び出しまたはユーザーによる入力によって引数が返される場合は、引数をメソッドに渡す前に検証する必要があります。

ArgumentOutOfRangeException は、次の方法で広く使用されています。

例外がスローされる ArgumentOutOfRangeException 条件は次のとおりです。

  • コレクションのメンバーをインデックス番号で取得しており、インデックス番号が無効です。

    これは例外の最も一般的な原因です ArgumentOutOfRangeException 。 通常、インデックス番号は次の 4 つの理由のいずれかで無効です。

    1. コレクションにはメンバーがなく、コードでは メンバーが存在することを前提としています。 次の例では、要素のないコレクションの最初の要素の取得を試みます。

      using System;
      using System.Collections.Generic;
      
      public class Example4
      {
         public static void Main()
         {
            var list = new List<string>();
            Console.WriteLine("Number of items: {0}", list.Count);
            try {
               Console.WriteLine("The first item: '{0}'", list[0]);
            }
            catch (ArgumentOutOfRangeException e) {
               Console.WriteLine(e.Message);
            }
         }
      }
      // The example displays the following output:
      //   Number of items: 0
      //   Index was out of range. Must be non-negative and less than the size of the collection.
      //   Parameter name: index
      
      open System
      
      
      let list = ResizeArray<string>()
      printfn $"Number of items: {list.Count}"
      try
          printfn $"The first item: '{list[0]}'"
      with 
      | :? ArgumentOutOfRangeException as e ->
          printfn $"{e.Message}"
      
      // The example displays the following output:
      //   Number of items: 0
      //   Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
      
      Imports System.Collections.Generic
      
      Module Example
         Public Sub Main()
            Dim list As New List(Of String)
            Console.WriteLine("Number of items: {0}", list.Count)
            Try
               Console.WriteLine("The first item: '{0}'", list(0))
            Catch e As ArgumentOutOfRangeException
               Console.WriteLine(e.Message)
            End Try
         End Sub
      End Module
      ' The example displays the following output:
      '   Number of items: 0
      '   Index was out of range. Must be non-negative and less than the size of the collection.
      '   Parameter name: index
      

      例外を回避するには、次のコード フラグメントのように、メンバーの取得を試みる前に、コレクションの Count プロパティが 0 より大きいかどうかをチェックします。

      if (list.Count > 0)
         Console.WriteLine("The first item: '{0}'", list[0]);
      
      if list.Count > 0 then
          printfn $"The first item: '{list[0]}'"
      
      If list.Count > 0 Then
         Console.WriteLine("The first item: '{0}'", list(0))
      End If
      
    2. 場合によっては、この目的のために存在する メソッド ( など Add) を呼び出すのではなく、存在しないインデックスを使用してコレクションにメンバーを追加しようとしているため、例外が発生することがあります。 次の例では、 メソッドを呼び出すのではなく、存在しないインデックスを使用して、コレクションに要素を List<T>.Add 追加しようとします。

      using System;
      using System.Collections.Generic;
      
      public class Example13
      {
         public static void Main()
         {
            var numbers = new List<int>();
            numbers.AddRange( new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 } );
      
            var squares = new List<int>();
            for (int ctr = 0; ctr < numbers.Count; ctr++)
               squares[ctr] = (int) Math.Pow(numbers[ctr], 2);
         }
      }
      // The example displays the following output:
      //    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
      //    Parameter name: index
      //       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
      //       at Example.Main()
      
      let numbers = ResizeArray<int>()
      numbers.AddRange [ 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 20 ]
      
      let squares = ResizeArray<int>()
      for  ctr = 0 to numbers.Count - 1 do
          squares[ctr] <- int (float numbers[ctr] ** 2)
      
      // The example displays the following output:
      //    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
      //       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
      //       at <StartupCode$argumentoutofrangeexception>.$NoElements.main@()
      
      Imports System.Collections.Generic
      
      Module Example
         Public Sub Main()
            Dim numbers As New List(Of Integer)
            numbers.AddRange( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 } )
            
            Dim squares As New List(Of Integer)
            For ctr As Integer = 0 To numbers.Count - 1
               squares(ctr) = CInt(numbers(ctr) ^ 2) 
            Next
         End Sub
      End Module
      ' The example displays the following output:
      '    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
      '    Parameter name: index
      '       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
      '       at Example.Main()
      

      次のコード フラグメントは、このエラーを修正します。

      var squares = new List<int>();
      for (int ctr = 0; ctr < numbers.Count; ctr++)
         squares.Add((int) Math.Pow(numbers[ctr], 2));
      
      let squares = ResizeArray<int>()
      for ctr = 0 to numbers.Count - 1 do
          squares.Add(int (float numbers[ctr] ** 2))
      
      Dim squares As New List(Of Integer)
      For ctr As Integer = 0 To numbers.Count - 1
         squares.Add(CInt(numbers(ctr) ^ 2)) 
      Next
      
    3. インデックスが負の項目を取得しようとしています。 これは通常、コレクションで特定の要素のインデックスを検索し、検索が成功したと誤って想定したために発生します。 次の例では、 メソッドの List<T>.FindIndex(Predicate<T>) 呼び出しで "Z" と等しい文字列が見つからないため、-1 が返されます。 ただし、これは無効なインデックス値です。

      using System;
      using System.Collections.Generic;
      
      public class Example
      {
         public static void Main()
         {
            var list = new List<string>();
            list.AddRange( new String[] { "A", "B", "C" } );
            // Get the index of the element whose value is "Z".
            int index = list.FindIndex((new StringSearcher("Z")).FindEquals);
            try {
               Console.WriteLine("Index {0} contains '{1}'", index, list[index]);
            }
            catch (ArgumentOutOfRangeException e) {
               Console.WriteLine(e.Message);
            }
         }
      }
      
      internal class StringSearcher
      {
         string value;
      
         public StringSearcher(string value)
         {
            this.value = value;
         }
      
         public bool FindEquals(string s)
         {
            return s.Equals(value, StringComparison.InvariantCulture);
         }
      }
      // The example displays the following output:
      //   Index was out of range. Must be non-negative and less than the size of the collection.
      //   Parameter name: index
      
      open System
      
      module StringSearcher =
          let findEquals (s: string) value =
              s.Equals(value, StringComparison.InvariantCulture)
      
      let list = ResizeArray<string>()
      list.AddRange [ "A"; "B"; "C" ]
      // Get the index of the element whose value is "Z".
      let index = list.FindIndex(StringSearcher.findEquals "Z")
      try 
          printfn $"Index {index} contains '{list[index]}'"
      with 
      | :? ArgumentOutOfRangeException as e ->
          printfn $"{e.Message}" 
      
      // The example displays the following output:
      //   Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
      
      Imports System.Collections.Generic
      
      Module Example
         Public Sub Main()
            Dim list As New List(Of String) 
            list.AddRange( { "A", "B", "C" } )
            ' Get the index of the element whose value is "Z".
            Dim index As Integer = list.FindIndex(AddressOf (New StringSearcher("Z")).FindEquals)
            Try
               Console.WriteLine("Index {0} contains '{1}'", index, list(index)) 
            Catch e As ArgumentOutOfRangeException
               Console.WriteLine(e.Message)
            End Try
         End Sub
      End Module
      
      Friend Class StringSearcher
         Dim value As String
         
         Public Sub New(value As String)
            Me.value = value
         End Sub
         
         Public Function FindEquals(s As String) As Boolean
            Return s.Equals(value, StringComparison.InvariantCulture) 
         End Function
      End Class
      ' The example displays the following output:
      '   Index was out of range. Must be non-negative and less than the size of the collection.
      '   Parameter name: index
      

      例外を回避するには、次のコード フラグメントのように、コレクションから項目を取得する前に、返されるインデックスが 0 以上であることを確認して、検索が成功したことをチェックします。

      // Get the index of the element whose value is "Z".
      int index = list.FindIndex((new StringSearcher("Z")).FindEquals);
      if (index >= 0)
         Console.WriteLine("'Z' is found at index {0}", list[index]);
      
      // Get the index of the element whose value is "Z".
      let index = list.FindIndex(StringSearcher.findEquals "Z")
      if index >= 0 then
          printfn $"'Z' is found at index {list[index]}"
      
      ' Get the index of the element whose value is "Z".
      Dim index As Integer = list.FindIndex(AddressOf (New StringSearcher("Z")).FindEquals)
      If index >= 0 Then
         Console.WriteLine("Index {0} contains '{1}'", index, list(index)) 
      End If
      
    4. 次の例に示すように、インデックスがコレクション Count の プロパティの値と等しい要素を取得しようとしています。

      using System;
      using System.Collections.Generic;
      
      public class Example8
      {
         public static void Main()
         {
            var list = new List<string>();
            list.AddRange( new String[] { "A", "B", "C" } );
            try {
               // Display the elements in the list by index.
               for (int ctr = 0; ctr <= list.Count; ctr++)
                  Console.WriteLine("Index {0}: {1}", ctr, list[ctr]);
            }
            catch (ArgumentOutOfRangeException e) {
               Console.WriteLine(e.Message);
            }
         }
      }
      // The example displays the following output:
      //   Index 0: A
      //   Index 1: B
      //   Index 2: C
      //   Index was out of range. Must be non-negative and less than the size of the collection.
      //   Parameter name: index
      
      open System
      
      let list = ResizeArray<string>()
      list.AddRange [ "A"; "B"; "C" ] 
      try
          // Display the elements in the list by index.
          for i = 0 to list.Count do
              printfn $"Index {i}: {list[i]}"
      with 
      | :? ArgumentOutOfRangeException as e ->
          printfn $"{e.Message}" 
            
      // The example displays the following output:
      //   Index 0: A
      //   Index 1: B
      //   Index 2: C
      //   Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
      
      Imports System.Collections.Generic
      
      Module Example
         Public Sub Main()
            Dim list As New List(Of String) 
            list.AddRange( { "A", "B", "C" } )
            Try
               ' Display the elements in the list by index.
               For ctr As Integer = 0 To list.Count
                  Console.WriteLine("Index {0}: {1}", ctr, list(ctr)) 
               Next   
            Catch e As ArgumentOutOfRangeException
               Console.WriteLine(e.Message)
            End Try
         End Sub
      End Module
      ' The example displays the following output:
      '   Index 0: A
      '   Index 1: B
      '   Index 2: C
      '   Index was out of range. Must be non-negative and less than the size of the collection.
      '   Parameter name: index
      

      .NET のコレクションでは 0 から始まるインデックス作成が使用されるため、コレクションの最初の要素はインデックス 0 で、最後の要素は index Count - 1 になります。 次のコードのように、インデックス Count - 1 の最後の要素に確実にアクセスすることで、エラーを排除できます。

      // Display the elements in the list by index.
      for (int ctr = 0; ctr < list.Count; ctr++)
         Console.WriteLine("Index {0}: {1}", ctr, list[ctr]);
      
      // Display the elements in the list by index.
      for i = 0 to list.Count - 1 do
          printfn $"Index {i}: {list[i]}"
      
      ' Display the elements in the list by index.
      For ctr As Integer = 0 To list.Count - 1 
         Console.WriteLine("Index {0}: {1}", ctr, list(ctr)) 
      Next
      
  • 文字列操作メソッドを呼び出して文字列操作を実行しようとしていますが、開始インデックスが文字列に存在しません。

    操作の開始インデックスを指定できる 、、IndexOfAnyString.InsertString.LastIndexOfString.LastIndexOfAnyRemoveString.Substring、 などのString.CompareString.CompareOrdinalString.IndexOfメソッドのオーバーロードでは、インデックスが文字列内の有効な位置である必要があります。 有効なインデックスの範囲は 0 String.Length ~ 1 です。

    この ArgumentOutOfRangeException 例外には、次の 4 つの一般的な原因があります。

    1. 空の文字列または String.Emptyを使用しています。 プロパティは String.Length 0 を返すので、インデックスによって操作しようとすると例外が ArgumentOutOfRangeException スローされます。 次の例では、文字列の GetFirstCharacter 最初の文字を返すメソッドを定義します。 文字列が空の場合、メソッドに渡される最後の文字列がであるため、メソッドは例外を ArgumentOutOfRangeException スローします。

      using System;
      
      public class Example1
      {
          public static void Main()
          {
              String[] words = { "the", "today", "tomorrow", " ", "" };
              foreach (var word in words)
                  Console.WriteLine("First character of '{0}': '{1}'",
                                    word, GetFirstCharacter(word));
          }
      
          private static char GetFirstCharacter(string s)
          {
              return s[0];
          }
      }
      // The example displays the following output:
      //    First character of //the//: //t//
      //    First character of //today//: //t//
      //    First character of //tomorrow//: //t//
      //    First character of // //: // //
      //
      //    Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
      //       at Example.Main()
      
      open System
      
      let getFirstCharacter (s: string) = s[0]
      
      let words = [ "the"; "today"; "tomorrow"; " "; "" ]
      for word in words do
          printfn $"First character of '{word}': '{getFirstCharacter word}'"
      
      // The example displays the following output:
      //    First character of 'the': 't'
      //    First character of 'today': 't'
      //    First character of 'tomorrow': 't'
      //    First character of ' ': ' '
      //
      //    Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
      //       at <StartupCode$argumentoutofrangeexception>.$EmptyString1.main@()
      
      Module Example
         Public Sub Main()
             Dim words() As String = { "the", "today", "tomorrow", " ", "" }
             For Each word In words
                Console.WriteLine("First character of '{0}': '{1}'", 
                                  word, GetFirstCharacter(word))
             Next                     
         End Sub
         
         Private Function GetFirstCharacter(s As String) As Char
            Return s(0)
         End Function
      End Module
      ' The example displays the following output:
      '    First character of 'the': 't'
      '    First character of 'today': 't'
      '    First character of 'tomorrow': 't'
      '    First character of ' ': ' '
      '    
      '    Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
      '       at Example.Main()
      

      例外を排除するには、文字列の String.Length が 0 より大きいかどうかをテストするか、 メソッドを IsNullOrEmpty 呼び出して、文字列が空でないことを null 確認します。 次のコード フラグメントは、後者を実行します。 この場合、文字列がまたは空の場合、GetFirstCharacterメソッドは null U+0000 を返します。

      static char GetFirstCharacter(string s)
      {
          if (string.IsNullOrEmpty(s))
              return '\u0000';
          else
              return s[0];
      }
      
      let getFirstCharacter (s: string) =
         if String.IsNullOrEmpty s then
            '\u0000'
         else
            s[0]
      
      Function GetFirstCharacter(s As String) As Char
         If String.IsNullOrEmpty(s) Then 
            Return ChrW(0)
         Else   
            Return s(0)
         End If   
      End Function
      
    2. その文字列内の部分文字列の位置に基づいて文字列を操作していて、部分文字列が実際に見つかったかどうかを判断できませんでした。

      次の使用例は、2 単語の語句の 2 番目の単語を抽出します。 語句が ArgumentOutOfRangeException 1 つの単語のみで構成され、埋め込みスペース文字が含まれていない場合は、例外がスローされます。 これは、 メソッドの呼び出しが -1 を String.IndexOf(String) 返して検索が失敗したことを示し、この無効な値が メソッドに渡されるために String.Substring(Int32) 発生します。

      using System;
      
      public class Example17
      {
         public static void Main()
         {
            String[] phrases = { "ocean blue", "concerned citizen",
                                 "runOnPhrase" };
            foreach (var phrase in phrases)
               Console.WriteLine("Second word is {0}", GetSecondWord(phrase));
         }
      
         static string GetSecondWord(string s)
         {
            int pos = s.IndexOf(" ");
            return s.Substring(pos).Trim();
         }
      }
      // The example displays the following output:
      //    Second word is blue
      //    Second word is citizen
      //
      //    Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
      //    Parameter name: startIndex
      //       at System.String.Substring(Int32 startIndex, Int32 length)
      //       at Example17.GetSecondWord(String s)
      //       at Example17.Main()
      
      let getSecondWord (s: string) =
          let pos = s.IndexOf " "
          s.Substring(pos).Trim()
      
      let phrases = [ "ocean blue"; "concerned citizen"; "runOnPhrase" ]
      for phrase in phrases do
          printfn $"Second word is {getSecondWord phrase}"
      
      // The example displays the following output:
      //    Second word is blue
      //    Second word is citizen
      //
      //    Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero. (Parameter 'startIndex')
      //       at System.String.Substring(Int32 startIndex, Int32 length)
      //       at System.String.Substring(Int32 startIndex)
      //       at NoFind1.getSecondWord(String s)
      //       at <StartupCode$argumentoutofrangeexception>.$NoFind1.main@()
      
      Module Example
         Public Sub Main()
            Dim phrases() As String = { "ocean blue", "concerned citizen", 
                                        "runOnPhrase" }
            For Each phrase In phrases
               Console.WriteLine("Second word is {0}", GetSecondWord(phrase))
            Next                            
        End Sub
        
        Function GetSecondWord(s As String) As String
           Dim pos As Integer = s.IndexOf(" ")
           Return s.Substring(pos).Trim()
        End Function
      End Module
      ' The example displays the following output:
      '       Second word is blue
      '       Second word is citizen
      '       
      '       Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
      '       Parameter name: startIndex
      '          at System.String.Substring(Int32 startIndex, Int32 length)
      '          at Example.GetSecondWord(String s)
      '          at Example.Main()
      

      例外を排除するには、文字列操作メソッドを呼び出す前に、文字列検索メソッドによって返される値を検証します。

      using System;
      
      public class Example18
      {
         public static void Main()
         {
            String[] phrases = { "ocean blue", "concerned citizen",
                                 "runOnPhrase" };
            foreach (var phrase in phrases) {
               string word = GetSecondWord(phrase);
               if (! string.IsNullOrEmpty(word))
                  Console.WriteLine("Second word is {0}", word);
            }
         }
      
         static string GetSecondWord(string s)
         {
            int pos = s.IndexOf(" ");
            if (pos >= 0)
               return s.Substring(pos).Trim();
            else
               return string.Empty;
         }
      }
      // The example displays the following output:
      //       Second word is blue
      //       Second word is citizen
      
      open System
      
      let getSecondWord (s: string) =
          let pos = s.IndexOf " "
          if pos >= 0 then
              s.Substring(pos).Trim()
          else 
              String.Empty
      
      let phrases = [ "ocean blue"; "concerned citizen"; "runOnPhrase" ]
      for phrase in phrases do
          let word = getSecondWord phrase
          if not (String.IsNullOrEmpty word) then
              printfn $"Second word is {word}"
      
      // The example displays the following output:
      //       Second word is blue
      //       Second word is citizen
      
      Module Example
         Public Sub Main()
            Dim phrases() As String = { "ocean blue", "concerned citizen", 
                                        "runOnPhrase" }
            For Each phrase In phrases
               Dim word As String = GetSecondWord(phrase)
               If Not String.IsNullOrEmpty(word) Then _
                  Console.WriteLine("Second word is {0}", word)
            Next                            
         End Sub
        
         Function GetSecondWord(s As String) As String
            Dim pos As Integer = s.IndexOf(" ")
            If pos >= 0
                Return s.Substring(pos).Trim()
            Else
               Return String.Empty
            End If
        End Function
      End Module
      ' The example displays the following output:
      '       Second word is blue
      '       Second word is citizen
      
    3. 現在の文字列の範囲外にある部分文字列を抽出しようとしました。

      部分文字列をすべて抽出するメソッドでは、部分文字列の開始位置と、文字列の末尾まで続かない部分文字列の部分文字列の文字数を指定する必要があります。 これは部分文字列の最後の文字の インデックス ではないことに注意してください。

      ArgumentOutOfRangeException部分文字列内の文字数が誤って計算されているため、通常、この場合は例外がスローされます。 検索メソッド String.IndexOf を使用して、部分文字列の開始位置と終了位置を識別する場合:

      • によって String.IndexOf 返される終了位置の文字を部分文字列に含める場合、部分文字列の終了位置は数式によって指定されます。

        endIndex - startIndex + 1
        
      • によって String.IndexOf 返される終了位置の文字が部分文字列から除外される場合、部分文字列の終了位置は数式によって指定されます。

        endIndex - startIndex
        

        次の例では、 メソッドを FindWords 使用 String.IndexOfAny(Char[], Int32) して文字列内のスペース文字と句読点を識別し、文字列内の単語を含む配列を返すメソッドを定義します。

        using System;
        using System.Collections.Generic;
        
        public class Example19
        {
           public static void Main()
           {
              string sentence = "This is a simple, short sentence.";
              Console.WriteLine("Words in '{0}':", sentence);
              foreach (var word in FindWords(sentence))
                 Console.WriteLine("   '{0}'", word);
           }
        
           static String[] FindWords(string s)
           {
              int start = 0, end = 0;
              Char[] delimiters = { ' ', '.', ',', ';', ':', '(', ')' };
              var words = new List<string>();
        
              while (end >= 0) {
                 end = s.IndexOfAny(delimiters, start);
                 if (end >= 0) {
                    if (end - start > 0)
                       words.Add(s.Substring(start, end - start));
        
                    start = end + 1;
                 }
                 else {
                    if (start < s.Length - 1)
                       words.Add(s.Substring(start));
                 }
              }
              return words.ToArray();
           }
        }
        // The example displays the following output:
        //       Words in 'This is a simple, short sentence.':
        //          'This'
        //          'is'
        //          'a'
        //          'simple'
        //          'short'
        //          'sentence'
        
        
        let findWords (s: string) =
            let mutable start, end' = 0, 0
            let delimiters = [| ' '; '.'; ','; ';'; ':'; '('; ')' |]
            let words = ResizeArray<string>()
            while end' >= 0 do
                end' <- s.IndexOfAny(delimiters, start)
                if end' >= 0 then
                    if end' - start > 0 then
                        words.Add(s.Substring(start, end' - start))
                    start <- end' + 1
                elif start < s.Length - 1 then
                    words.Add(s.Substring start)
            words.ToArray()
        
        let sentence = "This is a simple, short sentence."
        printfn $"Words in '{sentence}':"
        for word in findWords sentence do
            printfn $"   '{word}'"
        
        // The example displays the following output:
        //       Words in 'This is a simple, short sentence.':
        //          'This'
        //          'is'
        //          'a'
        //          'simple'
        //          'short'
        //          'sentence'
        
        Imports System.Collections.Generic
        
        Module Example
           Public Sub Main()
              Dim sentence As String = "This is a simple, short sentence."
              Console.WriteLine("Words in '{0}':", sentence)
              For Each word In FindWords(sentence)
                 Console.WriteLine("   '{0}'", word)
              Next
           End Sub
           
           Function FindWords(s As String) As String()
              Dim start, ending As Integer
              Dim delimiters() As Char = { " "c, "."c, ","c, ";"c, ":"c,
                                           "("c, ")"c }
              Dim words As New List(Of String)()
        
              Do While ending >= 0
                 ending = s.IndexOfAny(delimiters, start)
                 If ending >= 0
                    If ending - start > 0 Then
                       words.Add(s.Substring(start, ending - start)) 
                    End If
                    start = ending + 1
                 Else
                    If start < s.Length - 1 Then
                       words.Add(s.Substring(start))
                    End If      
                 End If
              Loop    
              Return words.ToArray()                         
           End Function
        End Module
        ' The example displays the following output:
        '       Words in 'This is a simple, short sentence.':
        '          'This'
        '          'is'
        '          'a'
        '          'simple'
        '          'short'
        '          'sentence'
        
  • 正の数値と 0 のみを必要とする引数を持つメソッドに負の数を渡したか、正の数値のみを必要とする引数を持つメソッドに負の数または 0 を渡しました。

    たとえば、 メソッドでは Array.CreateInstance(Type, Int32, Int32, Int32) 、2 次元配列の各次元の要素数を指定する必要があります。各次元の有効な値の範囲は 0 Int32.MaxValueから です。 ただし、次の例のディメンション引数には負の値があるため、 メソッドは例外を ArgumentOutOfRangeException スローします。

    using System;
    
    public class Example01
    {
        public static void Main()
        {
            int dimension1 = 10;
            int dimension2 = -1;
            try
            {
                Array arr = Array.CreateInstance(typeof(string),
                                                 dimension1, dimension2);
            }
            catch (ArgumentOutOfRangeException e)
            {
                if (e.ActualValue != null)
                    Console.WriteLine("{0} is an invalid value for {1}: ", e.ActualValue, e.ParamName);
                Console.WriteLine(e.Message);
            }
        }
    }
    // The example displays the following output:
    //     Non-negative number required.
    //     Parameter name: length2
    
    open System
    
    let dimension1 = 10
    let dimension2 = -1
    try
        let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)
        printfn "%A" arr
    with 
    | :? ArgumentOutOfRangeException as e ->
        if not (isNull e.ActualValue) then
            printfn $"{e.ActualValue} is an invalid value for {e.ParamName}: "
        printfn $"{e.Message}"
    
    // The example displays the following output:
    //     Non-negative number required. (Parameter 'length2')
    
    Module Example
       Public Sub Main()
          Dim dimension1 As Integer = 10
          Dim dimension2 As Integer = -1
          Try
             Dim arr AS Array = Array.CreateInstance(GetType(String), 
                                                     dimension1, dimension2)
          Catch e As ArgumentOutOfRangeException
             If e.ActualValue IsNot Nothing Then
                Console.WriteLine("{0} is an invalid value for {1}: ", 
                                  e.ActualValue, e.ParamName)
             End If                     
             Console.WriteLine(e.Message)
          End Try
       End Sub
    End Module
    ' The example displays the following output:
    '     Non-negative number required.
    '     Parameter name: length2
    

    エラーを修正するには、無効な引数の値が負以外であることを確認します。 これを行うには、次のコード フラグメントのように有効な値を指定します。

    int dimension1 = 10;
    int dimension2 = 10;
    Array arr = Array.CreateInstance(typeof(string),
                                     dimension1, dimension2);
    
    let dimension1 = 10
    let dimension2 = 10
    let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)
    printfn "%A" arr
    
    Dim dimension1 As Integer = 10
    Dim dimension2 As Integer = 10
    Dim arr As Array = Array.CreateInstance(GetType(String), 
                                            dimension1, dimension2)
    

    入力を検証し、無効な場合は何らかのアクションを実行することもできます。 次のコード フラグメントは、 メソッドを呼び出す代わりにエラー メッセージを表示します。

    if (dimension1 < 0 || dimension2 < 0)
    {
        Console.WriteLine("Unable to create the array.");
        Console.WriteLine("Specify non-negative values for the two dimensions.");
    }
    else
    {
        arr = Array.CreateInstance(typeof(string),
                                   dimension1, dimension2);
    }
    
    if dimension1 < 0 || dimension2 < 0 then
        printfn "Unable to create the array."
        printfn "Specify non-negative values for the two dimensions."
    else
        let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)
        printfn "%A" arr
    
    If dimension1 < 0 OrElse dimension2 < 0 Then
       Console.WriteLine("Unable to create the array.")
       Console.WriteLine("Specify non-negative values for the two dimensions.")
    Else
       arr = Array.CreateInstance(GetType(String), 
                                  dimension1, dimension2)   
    End If
    
  • 競合状態は、マルチスレッドであるか、非同期的に実行され、配列またはコレクションを更新するタスクを持つアプリに存在します。

    次の例では、 オブジェクトを List<T> 使用してオブジェクトの Continent コレクションを設定します。 コレクションが ArgumentOutOfRangeException 完全に設定される前に、コレクション内の 7 つの項目を表示しようとすると、 がスローされます。

    using System;
    using System.Collections.Generic;
    using System.Threading;
    
    public class Continent
    {
       public string? Name { get; set; }
       public int Population { get; set; }
       public Decimal Area { get; set; }
    }
    
    public class Example11
    {
       static List<Continent> continents = new List<Continent>();
       static string? s_msg;
    
       public static void Main()
       {
          String[] names = { "Africa", "Antarctica", "Asia",
                             "Australia", "Europe", "North America",
                             "South America" };
          // Populate the list.
          foreach (var name in names) {
             var th = new Thread(PopulateContinents);
             th.Start(name);
          }
          Console.WriteLine(s_msg);
          Console.WriteLine();
    
          // Display the list.
          for (int ctr = 0; ctr < names.Length; ctr++) {
             var continent = continents[ctr];
             Console.WriteLine("{0}: Area: {1}, Population {2}",
                               continent.Name, continent.Population,
                               continent.Area);
          }
       }
    
       private static void PopulateContinents(Object? obj)
       {
          string? name = obj?.ToString();
          s_msg += string.Format("Adding '{0}' to the list.\n", name);
          var continent = new Continent();
          continent.Name = name;
          // Sleep to simulate retrieving remaining data.
          Thread.Sleep(50);
          continents.Add(continent);
       }
    }
    // The example displays output like the following:
    //    Adding //Africa// to the list.
    //    Adding //Antarctica// to the list.
    //    Adding //Asia// to the list.
    //    Adding //Australia// to the list.
    //    Adding //Europe// to the list.
    //    Adding //North America// to the list.
    //    Adding //South America// to the list.
    //
    //
    //
    //    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    //    Parameter name: index
    //       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
    //       at Example.Main()
    
    open System.Threading
    
    type Continent =
        { Name: string
          Population: int
          Area: decimal }
    
    let continents = ResizeArray<Continent>()
    let mutable msg = ""
    
    let names = 
        [ "Africa"; "Antarctica"; "Asia"
          "Australia"; "Europe"; "North America"
          "South America" ]
    
    let populateContinents obj = 
        let name = string obj
        msg <- msg + $"Adding '{name}' to the list.\n"
        // Sleep to simulate retrieving data.
        Thread.Sleep 50
        let continent = 
            { Name = name
              Population = 0
              Area = 0M }
        continents.Add continent
          
    // Populate the list.
    for name in names do
        let th = Thread(ParameterizedThreadStart populateContinents)
        th.Start name
          
    printfn $"{msg}\n"
    
    // Display the list.
    for i = 0 to names.Length - 1 do
        let continent = continents[i]
        printfn $"{continent.Name}: Area: {continent.Population}, Population {continent.Area}"
    
    // The example displays output like the following:
    //    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
    //       at System.Collections.Generic.List`1.get_Item(Int32 index)
    //       at <StartupCode$argumentoutofrangeexception>.$Race1.main@()
    
    Imports System.Collections.Generic
    Imports System.Threading
    
    Public Class Continent
       Public Property Name As String
       Public Property Population As Integer
       Public Property Area As Decimal  
    End Class
    
    Module Example
       Dim continents As New List(Of Continent)
       Dim msg As String 
          
       Public Sub Main()
          Dim names() As String = { "Africa", "Antarctica", "Asia", 
                                         "Australia", "Europe", "North America",
                                         "South America" }
          ' Populate the list.
          For Each name In names
             Dim th As New Thread(AddressOf PopulateContinents)
             th.Start(name)
          Next              
          Console.WriteLine(msg)
          Console.WriteLine()
    
          ' Display the list.
          For ctr As Integer = 0 To names.Length - 1
             Dim continent = continents(ctr)
             Console.WriteLine("{0}: Area: {1}, Population {2}", 
                               continent.Name, continent.Population,
                               continent.Area)
          Next
       End Sub
       
       Private Sub PopulateContinents(obj As Object)
          Dim name As String = obj.ToString()
          msg += String.Format("Adding '{0}' to the list.{1}", name, vbCrLf)
          Dim continent As New Continent()
          continent.Name = name
          ' Sleep to simulate retrieving remaining data.
          Thread.Sleep(50)
          continents.Add(continent)
       End Sub
    End Module
    ' The example displays output like the following:
    '    Adding 'Africa' to the list.
    '    Adding 'Antarctica' to the list.
    '    Adding 'Asia' to the list.
    '    Adding 'Australia' to the list.
    '    Adding 'Europe' to the list.
    '    Adding 'North America' to the list.
    '    Adding 'South America' to the list.
    '    
    '    
    '    
    '    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    '    Parameter name: index
    '       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
    '       at Example.Main()
    

    この場合、複数のスレッドから 2 つのリソースにアクセスします。

    • continents コレクションです。 その List<T>.Add メソッドは、複数のスレッドから呼び出されます。 さらに、メインまたはプライマリ スレッドは、メンバーを反復処理するときに、コレクションに 7 つの要素が完全に設定されていることを前提としています。

    • 複数の msg スレッドから連結される文字列。

    エラーを修正するには、次のように、共有状態がスレッド セーフな方法でアクセスされていることを確認します。

    • アプリで配列またはコレクション オブジェクトを使用する場合は、名前空間の型 System.Collections.Concurrent や帯域外リリースなど、スレッド セーフなコレクション クラスの使用を System.Collections.Immutable 検討してください。

    • 共有状態 (つまり、複数のスレッドがアクセスできるリソース) にスレッド セーフな方法でアクセスし、一度に 1 つのスレッドのみがリソースに排他的にアクセスできるようにします。 リソースへのアクセスを同期するために、、 InterlockedMonitorMutexなどのCountdownEvent多数のクラスを使用できます。 詳細については、「 スレッド処理」を参照してください。 さらに、言語のサポートは、C# の lock ステートメントと Visual Basic の SyncLock コンストラクトを通じて利用できます。

    次の例では、前の ArgumentOutOfRangeException 例の およびその他の問題に対処します。 オブジェクトを List<T> オブジェクト ConcurrentBag<T> に置き換えて、コレクションへのアクセスがスレッド セーフであることを確認し、オブジェクトを CountdownEvent 使用して他のスレッドが実行された後にのみアプリケーション スレッドが続行されるようにし、ロックを使用して一度に 1 つのスレッドのみが変数にアクセス msg できるようにします。

    using System;
    using System.Collections.Concurrent;
    using System.Threading;
    
    public class ContinentD
    {
       public string? Name { get; set; }
       public int Population { get; set; }
       public Decimal Area { get; set; }
    }
    
    public class Example12
    {
       static ConcurrentBag<ContinentD> ContinentDs = new ConcurrentBag<ContinentD>();
       static CountdownEvent? gate;
       static string msg = string.Empty;
    
       public static void Main()
       {
          String[] names = { "Africa", "Antarctica", "Asia",
                             "Australia", "Europe", "North America",
                             "South America" };
          gate = new CountdownEvent(names.Length);
    
          // Populate the list.
          foreach (var name in names) {
             var th = new Thread(PopulateContinentDs);
             th.Start(name);
          }
    
          // Display the list.
          gate.Wait();
          Console.WriteLine(msg);
          Console.WriteLine();
    
          var arr = ContinentDs.ToArray();
          for (int ctr = 0; ctr < names.Length; ctr++) {
             var ContinentD = arr[ctr];
             Console.WriteLine("{0}: Area: {1}, Population {2}",
                               ContinentD.Name, ContinentD.Population,
                               ContinentD.Area);
          }
       }
    
       private static void PopulateContinentDs(Object? obj)
       {
          string? name = obj?.ToString();
          lock(msg) {
             msg += string.Format("Adding '{0}' to the list.\n", name);
          }
          var ContinentD = new ContinentD();
          ContinentD.Name = name;
          // Sleep to simulate retrieving remaining data.
          Thread.Sleep(25);
          ContinentDs.Add(ContinentD);
          gate?.Signal();
       }
    }
    // The example displays output like the following:
    //       Adding 'Africa' to the list.
    //       Adding 'Antarctica' to the list.
    //       Adding 'Asia' to the list.
    //       Adding 'Australia' to the list.
    //       Adding 'Europe' to the list.
    //       Adding 'North America' to the list.
    //       Adding 'South America' to the list.
    //
    //
    //       Africa: Area: 0, Population 0
    //       Antarctica: Area: 0, Population 0
    //       Asia: Area: 0, Population 0
    //       Australia: Area: 0, Population 0
    //       Europe: Area: 0, Population 0
    //       North America: Area: 0, Population 0
    //       South America: Area: 0, Population 0
    
    open System.Collections.Concurrent
    open System.Threading
    
    type Continent =
        { Name: string
          Population: int
          Area: decimal }
    
    let continents = ConcurrentBag<Continent>();
    let mutable msg = ""
    
    let names = 
        [ "Africa"; "Antarctica"; "Asia"
          "Australia"; "Europe"; "North America"
          "South America" ]
    
    let gate = new CountdownEvent(names.Length)
    
    let populateContinents obj = 
        let name = string obj
        lock msg (fun () -> 
            msg <- msg + $"Adding '{name}' to the list.\n" )
    
        // Sleep to simulate retrieving remaining data.
        let continent = 
            { Name = name
              Population = 0
              Area = 0M }
        Thread.Sleep 25
        continents.Add continent
        gate.Signal() |> ignore
    
    // Populate the list.
    for name in names do
        let th = Thread(ParameterizedThreadStart populateContinents)
        th.Start name
    
    // Display the list.
    gate.Wait();
    printfn $"{msg}\n"
    
    let arr = continents.ToArray();
    for i = 0 to names.Length - 1 do
        let continent = arr[i]
        printfn $"{continent.Name}: Area: {continent.Population}, Population {continent.Area}"
    
    // The example displays output like the following:
    //       Adding 'Africa' to the list.
    //       Adding 'Antarctica' to the list.
    //       Adding 'Asia' to the list.
    //       Adding 'Australia' to the list.
    //       Adding 'Europe' to the list.
    //       Adding 'North America' to the list.
    //       Adding 'South America' to the list.
    //
    //
    //       Africa: Area: 0, Population 0
    //       Antarctica: Area: 0, Population 0
    //       Asia: Area: 0, Population 0
    //       Australia: Area: 0, Population 0
    //       Europe: Area: 0, Population 0
    //       North America: Area: 0, Population 0
    //       South America: Area: 0, Population 0
    
    Imports System.Collections.Concurrent
    Imports System.Threading
    
    Public Class Continent
       Public Property Name As String
       Public Property Population As Integer
       Public Property Area As Decimal  
    End Class
    
    Module Example
       Dim continents As New ConcurrentBag(Of Continent)
       Dim gate As CountdownEvent
       Dim msg As String = String.Empty
          
       Public Sub Main()
          Dim names() As String = { "Africa", "Antarctica", "Asia", 
                                    "Australia", "Europe", "North America",
                                    "South America" }
          gate = new CountdownEvent(names.Length)
          
          ' Populate the list.
          For Each name In names
             Dim th As New Thread(AddressOf PopulateContinents)
             th.Start(name)
          Next              
    
          ' Display the list.
          gate.Wait()
          Console.WriteLine(msg)
          Console.WriteLine()
    
          For ctr As Integer = 0 To names.Length - 1
             Dim continent = continents(ctr)
             Console.WriteLine("{0}: Area: {1}, Population {2}", 
                               continent.Name, continent.Population,
                               continent.Area)
          Next
       End Sub
       
       Private Sub PopulateContinents(obj As Object)
          Dim name As String = obj.ToString()
          SyncLock msg 
             msg += String.Format("Adding '{0}' to the list.{1}", name, vbCrLf)
          End SyncLock
          Dim continent As New Continent()
          continent.Name = name
          ' Sleep to simulate retrieving remaining data.
          Thread.Sleep(25)
          continents.Add(continent)
          gate.Signal()
       End Sub
    End Module
    ' The example displays output like the following:
    '    Adding 'Africa' to the list.
    '    Adding 'Antarctica' to the list.
    '    Adding 'Asia' to the list.
    '    Adding 'Australia' to the list.
    '    Adding 'Europe' to the list.
    '    Adding 'North America' to the list.
    '    Adding 'South America' to the list.
    '    
    '    
    '    Africa: Area: 0, Population 0
    '    Antarctica: Area: 0, Population 0
    '    Asia: Area: 0, Population 0
    '    Australia: Area: 0, Population 0
    '    Europe: Area: 0, Population 0
    '    North America: Area: 0, Population 0
    '    South America: Area: 0, Population 0
    

ArgumentOutOfRangeException では、0X80131502値を持つ HRESULT COR_E_ARGUMENTOUTOFRANGEが使用されます。

インスタンスの初期プロパティ値の一覧についてはArgumentOutOfRangeExceptionを参照してください、ArgumentOutOfRangeExceptionコンス トラクター。

コンストラクター

ArgumentOutOfRangeException()

ArgumentOutOfRangeException クラスの新しいインスタンスを初期化します。

ArgumentOutOfRangeException(SerializationInfo, StreamingContext)
古い.

シリアル化したデータを使用して、ArgumentOutOfRangeException クラスの新しいインスタンスを初期化します。

ArgumentOutOfRangeException(String)

この例外の原因である引数の名前を指定して、ArgumentOutOfRangeException クラスの新しいインスタンスを初期化します。

ArgumentOutOfRangeException(String, Exception)

エラー メッセージ、およびこの例外の原因である例外を指定して、ArgumentOutOfRangeException クラスの新しいインスタンスを初期化します。

ArgumentOutOfRangeException(String, Object, String)

パラメーター名、引数の値、および指定されたエラー メッセージを使用して、ArgumentOutOfRangeException クラスの新しいインスタンスを初期化します。

ArgumentOutOfRangeException(String, String)

この例外の原因となるパラメーターの名前と、指定したエラー メッセージを使用して、ArgumentOutOfRangeException クラスの新しいインスタンスを初期化します。

プロパティ

ActualValue

この例外の原因である引数値を取得します。

Data

例外に関する追加のユーザー定義情報を提供する、キーと値のペアのコレクションを取得します。

(継承元 Exception)
HelpLink

この例外に関連付けられているヘルプ ファイルへのリンクを取得または設定します。

(継承元 Exception)
HResult

特定の例外に割り当てられているコード化数値である HRESULT を取得または設定します。

(継承元 Exception)
InnerException

現在の例外の原因となる Exception インスタンスを取得します。

(継承元 Exception)
Message

エラー メッセージおよび無効な引数値の文字列形式を取得します。引数値が null の場合は、エラー メッセージだけを取得します。

ParamName

この例外の原因である引数の名前を取得します。

(継承元 ArgumentException)
Source

エラーの原因となるアプリケーションまたはオブジェクトの名前を取得または設定します。

(継承元 Exception)
StackTrace

呼び出し履歴で直前のフレームの文字列形式を取得します。

(継承元 Exception)
TargetSite

現在の例外がスローされたメソッドを取得します。

(継承元 Exception)

メソッド

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetBaseException()

派生クラスでオーバーライドされた場合、それ以後に発生する 1 つ以上の例外の根本原因である Exception を返します。

(継承元 Exception)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetObjectData(SerializationInfo, StreamingContext)
古い.

無効な引数値と追加の例外情報を使用して SerializationInfo オブジェクトを設定します。

GetObjectData(SerializationInfo, StreamingContext)
古い.

パラメーター名と追加の例外情報を使用して SerializationInfo オブジェクトを設定します。

(継承元 ArgumentException)
GetType()

現在のインスタンスのランタイム型を取得します。

(継承元 Exception)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
ThrowIfEqual<T>(T, T, String)

ArgumentOutOfRangeExceptionが と等しい場合valueは をotherスローします。

ThrowIfGreaterThan<T>(T, T, String)

が よりother大きい場合valueは をArgumentOutOfRangeExceptionスローします。

ThrowIfGreaterThanOrEqual<T>(T, T, String)

ArgumentOutOfRangeExceptionが 以上の場合valueは をスローしますother

ThrowIfLessThan<T>(T, T, String)

が よりother小さい場合valueは をArgumentOutOfRangeExceptionスローします。

ThrowIfLessThanOrEqual<T>(T, T, String)

ArgumentOutOfRangeExceptionが 以下の場合valueは をスローしますother

ThrowIfNegative<T>(T, String)

が負の場合valueは をArgumentOutOfRangeExceptionスローします。

ThrowIfNegativeOrZero<T>(T, String)

が負またはゼロの場合valueは をArgumentOutOfRangeExceptionスローします。

ThrowIfNotEqual<T>(T, T, String)

ArgumentOutOfRangeExceptionが と等しくない場合valueは、 をotherスローします。

ThrowIfZero<T>(T, String)

が 0 の場合valueは をArgumentOutOfRangeExceptionスローします。

ToString()

現在の例外の文字列形式を作成して返します。

(継承元 Exception)

イベント

SerializeObjectState
古い.

例外がシリアル化され、例外に関するシリアル化されたデータを含む例外状態オブジェクトが作成されたときに発生します。

(継承元 Exception)

適用対象

こちらもご覧ください