c# - 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());
}
}
}
解决方案
删除覆盖.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)
{
}
}
推荐阅读
- vue.js - Vue 3 - 更新 shallowReactive 数组的官方方法
- reactjs - 通过输入事件将图像加载到 img
- php - PHP防止浮动轮
- python - 如何从 RDD 中提取元组?
- d3.js - d3 在没有 npm 的情况下集成到 openlayers
- c# - System.IO.IOException 使用 itext 写入 PDF 文件
- python - 有没有办法设置属性的属性?
- python - 从具有 2 个预测变量的分层模型中绘制多个散点图
- c++ - How to get the number of items used in an unbounded knapsack problem?
- java - How to access website deployed on Google cloud VM?