You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#程序输入无效姓名和手机号时仅姓名异常抛出,手机号校验未执行

问题原因

当前代码在同一个try块中依次校验姓名和手机号,当姓名校验失败抛出InvalidName异常时,程序流程会立即跳转到对应的catch块,后续的手机号校验代码完全不会执行,因此无法检测到手机号的错误。

解决思路

要同时校验姓名和手机号并输出所有错误,需要先完成所有校验逻辑,收集全部错误后再统一处理,而不是中途抛出异常中断流程。

实现方案

方案1:直接收集并输出所有错误(无需异常)

修改Main方法,先分别完成姓名和手机号的校验,将错误信息存入列表,最后统一输出所有错误:

using System;
using System.Collections.Generic;
using System.Linq;

namespace exercise1
{
    public class Contact
    {
        // 改用C#属性规范,替代原有的get方法
        public string Name { get; }
        public string PhoneNo { get; }

        public Contact(string n, string p)
        {
            Name = n;
            PhoneNo = p;
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your name");
            string name = Console.ReadLine();
            Console.WriteLine("Enter your phone number");
            string phoneNo = Console.ReadLine();
            Contact c = new Contact(name, phoneNo);

            var validationErrors = new List<string>();

            // 校验姓名
            if (string.IsNullOrWhiteSpace(c.Name) || c.Name.Any(char.IsDigit))
            {
                validationErrors.Add("Name not valid");
            }

            // 校验手机号
            if (string.IsNullOrWhiteSpace(c.PhoneNo) || c.PhoneNo.Length != 10 || !c.PhoneNo.All(char.IsDigit))
            {
                validationErrors.Add("phone number not valid");
            }

            // 处理结果
            if (validationErrors.Count > 0)
            {
                foreach (var error in validationErrors)
                {
                    Console.WriteLine(error);
                }
            }
            else
            {
                Console.WriteLine("Checked name");
                Console.WriteLine("Phone number is valid");
                Console.WriteLine("Checked phoneno");
            }
        }
    }

    // 保留原自定义异常(如果后续需要单独抛出时使用)
    public class InvalidName : Exception
    {
        public InvalidName(string msg) : base(msg) { }
    }

    public class InvalidPhone : Exception
    {
        public InvalidPhone(string msg) : base(msg) { }
    }
}

方案2:自定义多错误异常(保留异常处理逻辑)

如果希望继续使用异常机制,可以定义一个包含多个错误信息的自定义异常,收集完所有错误后统一抛出:

using System;
using System.Collections.Generic;
using System.Linq;

namespace exercise1
{
    public class Contact
    {
        public string Name { get; }
        public string PhoneNo { get; }

        public Contact(string n, string p)
        {
            Name = n;
            PhoneNo = p;
        }
    }

    // 新增包含多错误的自定义异常
    public class ValidationFailedException : Exception
    {
        public List<string> Errors { get; }

        public ValidationFailedException(List<string> errors) : base("Validation failed with multiple errors")
        {
            Errors = errors;
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your name");
            string name = Console.ReadLine();
            Console.WriteLine("Enter your phone number");
            string phoneNo = Console.ReadLine();
            Contact c = new Contact(name, phoneNo);

            var validationErrors = new List<string>();

            if (string.IsNullOrWhiteSpace(c.Name) || c.Name.Any(char.IsDigit))
            {
                validationErrors.Add("Name not valid");
            }

            if (string.IsNullOrWhiteSpace(c.PhoneNo) || c.PhoneNo.Length != 10 || !c.PhoneNo.All(char.IsDigit))
            {
                validationErrors.Add("phone number not valid");
            }

            try
            {
                if (validationErrors.Count > 0)
                {
                    throw new ValidationFailedException(validationErrors);
                }

                Console.WriteLine("Checked name");
                Console.WriteLine("Phone number is valid");
                Console.WriteLine("Checked phoneno");
            }
            catch (ValidationFailedException ex)
            {
                foreach (var error in ex.Errors)
                {
                    Console.WriteLine(error);
                }
            }
        }
    }

    public class InvalidName : Exception
    {
        public InvalidName(string msg) : base(msg) { }
    }

    public class InvalidPhone : Exception
    {
        public InvalidPhone(string msg) : base(msg) { }
    }
}

内容的提问来源于stack exchange,提问作者riri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:52:05