常见异常 – ArgumentOutOfRangeException

发布日期:2026-07-14 19:32:04   来源 : 杭州电子商务研究院    浏览量 :12
杭州电子商务研究院 发布日期:2026-07-14 19:32:04  
12

介绍

异常是程序中违反系统或应用程序约束的运行时错误,或者是程序正常执行期间不应发生的情况。异常的可能原因包括当程序试图将数字除以零时尝试连接到不再存在的数据库,或者打开损坏的 XML 文件。当发生这些情况时,系统会捕获错误并引发异常。捕获异常是一种处理这些意外错误的方法,方法是定义在引发异常时运行的代码块。

有一些常见的异常类型值得注意。在本指南中,我们将介绍ArgumentOutOfRangeException异常类型。

遇到 ArgumentOutOfRangeException 异常类型

当传递给方法的参数不为且包含的值不在预期值范围内时,会引发 ArgumentOutOfRangeException 异常。此异常类型具有属性ParamNameActualValue帮助了解异常的原因。ParamName属性标识无效参数的参数名称,ActualValue属性标识无效值(如果存在值)。

ArgumentOutOfRangeException异常通常是由开发人员错误导致的,如果参数的值在传递给引发异常的方法之前由方法调用或用户输入返回,则应在将参数传递给方法之前对其进行验证。ArgumentOutOfRangeException 被System.Collections命名空间中的类广泛使用。一个典型的场景是当您的代码想要从集合中删除某个索引处的项目时,而该集合为空,或者您通过参数指定的索引为负数或大于集合的大小。以下示例演示了这一点:

      using System;
using System.Collections.Generic;

class Program
{
  static void Main(string[] args)
  {
    try
    {
      var numbers = new List<int>();
      var index = 0;
      Console.WriteLine("Removing item at index {0}", index);

      numbers.RemoveAt(index);
    }
    catch (ArgumentOutOfRangeException ex)
    {
      Console.WriteLine("Oh no! Something went wrong");
      Console.WriteLine(ex);
    }
  }
}
    

运行上述示例时将显示以下输出:

      Removing item at index 0
Oh no! Something went wrong
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.Collections.Generic.List`1.RemoveAt(Int32 index)
   at MyApp.Program.Main(String[] args) in /dotnet/MyApp/Program.cs:line 13
    

为了防止出现异常,我们可以在尝试删除集合中的任何成员之前检查集合的Count属性是否大于零,并且要删除的索引是否也小于Count中的值。我们将更新try块内的代码语句,如下所示:

      var numbers = new List<int>() { 1, 2 };
var index = 2;
Console.WriteLine("Attempting to remove item at index {0}", index);

if (numbers.Count > 0 && index < numbers.Count)
{
  numbers.RemoveAt(index);
  Console.WriteLine("Removed item at index {0}", index);
}
    

这将帮助我们避免遇到异常。有关导致ArgumentOutOfRangeException异常的更多场景,请阅读文档

引发 ArgumentOutOfRangeException 异常类型

虽然ArgumentOutOfRangeExceptionSystem.CollectionsSystem.IO命名空间中的类、Array 类以及String类中的字符串操作方法广泛使用,但我们也可以使用它在代码中抛出异常,以表示参数的值超出了预期范围。让我们看一个如何使用它的示例。创建一个新的控制台应用程序项目并使用以下代码更新Program.cs 。

      namespace MyApp
{
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Enter account name");
                var name = Console.ReadLine();

                Console.WriteLine("Enter opening balance");
                var balance = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Opening account for {0}... \n", name);
                var account = new Account(name, balance);
                Console.WriteLine("Account opened for {0}", account.Name);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Console.WriteLine("Oh no! Something went wrong");
                Console.WriteLine(ex);
            }
        }

        class Account
        {
            public Account(string name, int balance)
            {
                if (balance < 1200)
                    throw new ArgumentOutOfRangeException(nameof(balance), balance, "The account balance can't be less than 1200");
                Name = name;
                Balance = balance;
            }
            public string Name { get; private set; }
            public int Balance { get; private set; }
        }
    }
}
    

在上面的代码中,我们有一个具有属性NameBalance的Account类,以及一个接受namebalance作为参数的构造函数。当此构造函数的余额小于 1200 时,它将抛出ArgumentOutOfRangeException异常,其中包含导致异常的参数名称、参数的值以及解释错误原因的消息。在静态Main方法中,我们从用户那里收集姓名和余额,然后使用这些信息创建一个Account对象。

如果我们运行应用程序并输入小于 1200 的余额值,我们将收到异常。以下信息是当我们以 900 作为余额运行代码时得到的信息。

      Enter account name
Philly
Enter opening balance
900
Opening account for Philly...

Oh no! Something went wrong
System.ArgumentOutOfRangeException: The account balance can't be less than 1200
Parameter name: balance
Actual value was 900.
   at MyApp.Program.Account..ctor(String name, Int32 balance) in /dotnet/MyApp/Program.cs:line 34
   at MyApp.Program.Main(String[] args) in /dotnet/MyApp/Program.cs:line 18
    

就此结束

当参数值超出调用方法定义的预期值范围时,会引发 ArgumentOutOfRangeException 异常。ArgumentOutOfRangeException 异常通常开发人员错误导致,因此在处理此类错误时,请务必读取属性MessageParamNameActualValue的值。如果参数值在传递给引发异常的方法之前从方法调用或用户输入返回,则应在将参数传递给方法之前对其进行验证。

我们研究了调用集合的RemoveAt方法可能导致此异常的情况以及如何解决该错误。我还展示了一个示例,演示了何时从方法中抛出 ArgumentOutOfRangeException 会很有用这应该让您能够处理和利用这种异常类型!

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据