常见的异常-ArgumentException、ArgumentNullException 和 ArgumentOutOfRangeException

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

介绍

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

有一些常见的异常类型值得注意。在本指南中,我们将介绍其中三种。它们是ArgumentException异常类型、ArgumentNullException异常类型和ArgumentOutOfRangeException异常类型。

ArgumentException 类型

当方法参数收到无效的参数值时,会抛出 ArgumentException 类型。此异常类型继承自System.SystemException类,而后者又派生自System.Exception基类。以下代码是抛出ArgumentException类型的示例应用程序。

      using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter first name");
            var firstName = Console.ReadLine();

            Console.WriteLine("Enter last name");
            var lastName = Console.ReadLine();

            try
            {
                var fullName = GetFullName(firstName, lastName);
                Console.WriteLine($"Your fullname is {fullName}");
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Oh no, Something went wrong");
                Console.WriteLine(ex);
            }
        }

        static string GetFullName(string firstName, string lastName)
        {
            if (firstName == "" || lastName == "") throw new ArgumentException ("first & last name arguments cannot be empty");
            return $"{firstName} {lastName}";
        }
    }
}
    

GetFullName方法有两个参数,firstNamelastName,它会检查这两个参数中是否有一个是空字符串。如果其中一个为真,则会抛出ArgumentException类型的异常。我们使用了将异常消息作为唯一参数的构造函数。我们上面设置的异常消息对于了解哪个参数导致了异常没有太大帮助。如果我们能知道哪个参数导致了错误,从而更容易修复错误,那不是更好吗?

ArgumentException类有一个ParamName属性,用于标识无效参数。这将是参数的名称。有了这些知识,我们可以更新GetFullName方法如下所示。

      static string GetFullName(string firstName, string lastName)
{
    if (firstName == "") throw new ArgumentException("empty string is an invalid value", "firstName");
    if (lastName == "") throw new ArgumentException("empty string is an invalid value", "lastName");

    return $"{firstName} {lastName}";
}
    

如果您运行该应用程序并为名字传递一个空字符串,您将收到以下错误:

      Oh no, Something went wrong

System.ArgumentException: empty string is an invalid value
Parameter name: firstName
   at MyApp.Program.GetFullName(String firstName, String lastName) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 30
   at MyApp.Program.Main(String[] args) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 17
    

您可以看到它在参数名称旁边打印了异常消息。

ArgumentNullException 类型

ArgumentNullException异常类型派生自ArgumentException类。当将空值传递给方法参数并且该参数不允许为空时,会引发此类异常。为了说明这一点,让我们创建一个控制台应用程序并使用以下代码更新Program.cs :

      using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var user = new User(null, 23);
            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine("Oh no, Something went wrong");
                Console.WriteLine(ex);
            }
        }

        class User
        {
            public User(string userName, int age)
            {
                if (userName == null)
                    throw new ArgumentNullException(nameof(userName), "username is invalid");

                UserName = userName;
                Age = age;
            }
            public string UserName { get; private set; }
            public int Age { get; private set; }
        }
    }
}
    

我们定义一个具有UserNameAge属性的User类。在类构造函数中,我们接受两个参数并将它们分配给适当的属性。在分配之前,我们检查userName是否为空。如果是,我们抛出一个ArgumentNullException异常。我们调用ArgumentNullException的构造函数,它接受导致异常的参数名称和表示异常消息的第二个参数。您可能已经注意到我们使用 nameof 运算符来获取导致异常的参数的字符串名称。使用nameof运算符有助于在重命名定义时保持代码有效。

如果你运行该应用程序,它会抛出异常,因为userName为空。它会在控制台中打印异常信息。

      Oh no, Something went wrong

System.ArgumentNullException: username is invalid
Parameter name: userName
   at MyApp.Program.User..ctor(String userName, Int32 age) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 27
   at MyApp.Program.Main(String[] args) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 11
    

ArgumentOutOfRangeException 类型

ArgumentOutOfRangeException类型是ArgumentException类的子类。当参数的值超出允许范围时,会抛出此异常类型。例如,当您将负数传递给仅接受正数的函数时,可能会抛出此异常。

为了演示此类型的用法,我们将继续使用上一节中的示例应用程序。编辑User类的构造函数如下:

      public User(string userName, int age)
{
    if (userName == null)
        throw new ArgumentNullException(nameof(userName), "username is invalid");
    if (age < 18 || age > 50)
        throw new ArgumentNullException(nameof(age), "age is outside the allowable range");

    UserName = userName;
    Age = age;
}
    

当年龄参数小于 18 或大于 50 时,上述代码将引发异常。

包起来

异常可能由运行时或应用程序代码抛出。这可能是由错误代码引起的,而其他时候,问题是由应用程序代码中未考虑到的错误用户输入引起的。在本指南中,我们研究了三种常见的异常类型。它们是ArgumentExceptionArgumentNullExceptionArgumentOutOfRangeException。它们可能由公共语言运行时 (CLR) 或其他类库抛出,表示开发人员错误。

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