首页 > 解决方案 > Exception.Cannot 打印异常字符串的问题,因为 Exception.ToString() 失败

问题描述

我目前正在练习创建我的异常类。这段代码的想法是让用户输入密码。如果其代码少于 5 个字符,程序将抛出异​​常。我希望我的程序抛出一个带有文本的异常(“密码太小”),并且我的 Exception 类的对象使用 ToString 方法(将在哪里写“密码长度异常”)。让我感到困惑的是为什么我会收到消息未处理的异常.Password 长度异常。无法打印异常字符串,因为 Exception.ToString () 失败。你可以在照片中看到这个

在此处输入图像描述 这是我的代码。

 public class My_Exception : Exception
    {
        
        public My_Exception(string message) : base(message)
        {
            Console.WriteLine(message);
        }
        
        public override string ToString()
        {
            throw new My_Exception(" Password Length exception ");
        }


    }



    class Program
    {
          
      static void Main(string[] args)
        
        {
           try
            {
                Console.WriteLine("Enter your password");
                string Password = Console.ReadLine();
                if (Password.Length < 5)
                {
                   throw new My_Exception(" Password is too small ");
                }
            }

            catch(My_Exception ex)
            {

             Console.WriteLine(ex.ToString());
            }

        }
    }

标签: c#

解决方案


删除覆盖.ToString().

public class My_Exception : Exception
{        
    public My_Exception(string message) : base(message)
    {
        Console.WriteLine(message);
    }       
}

message将由 base显示Exception.ToString()。你不应该从另一个异常中抛出异常。

事实上,你不应该Console.WriteLine()Exception. 它是try/catch块,应该以任何它想要异常的方式打印。

public class My_Exception : Exception
{        
    public My_Exception(string message) : base(message)
    {
    }       
}

请参阅https://ideone.com/FchSGc上的运行示例


推荐阅读