[英]In C# a Try block, the catch section i want a exception to be thrown if in my textbock a int is entered?
So if you push the enter button, and the user enters a number i want the program to throw out a exception that no integers may be entered in the text block. 因此,如果您按下回车按钮,并且用户输入了数字,我希望程序抛出一个例外,即在文本块中不得输入整数。
private void btnEnter_Click(object sender, RoutedEventArgs e)
{
try
{
string[] words = { txtInfo.Text };
foreach (string f in words)
{
lstResults.Items.Add(f);
}
txtInfo.Text = "";
}
catch (Exception ex)
{
}
}
Very small project for school but would like to specify the exception. 学校很小的项目,但想指定例外。
the best way to do this is to implement Guard Clauses. 最好的方法是实施警卫条款。 Guard Clause is just a simple checking of the input parameters at the top of your method. Guard子句只是对方法顶部的输入参数的简单检查。
I would totally remove try catch from your code and just check if the text in the box is an integer. 我会从您的代码中完全删除try catch,仅检查框中的文本是否为整数。
private void btnEnter_Click(object sender, RoutedEventArgs e)
{
//this will check if the text from the box can be parsed as an integer then
//exit this method but show message box with your message.
if(int.TryParse(txtInfo.Text, out var test)
{
MessageBox.Show("Integers are not allowed");
return;
}
string[] words = { txtInfo.Text };
foreach (string f in words)
{
lstResults.Items.Add(f);
}
txtInfo.Text = "";
}
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.