c# - 在 C# 的 Try 块中,如果在我的文本框中输入了一个 int,我希望抛出异常的 catch 部分?
问题描述
因此,如果您按下回车按钮,并且用户输入了一个数字,我希望程序抛出一个异常,即不能在文本块中输入整数。
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)
{
}
}
非常小的学校项目,但想指定例外。
解决方案
最好的方法是实现 Guard Clauses。Guard Clause 只是对方法顶部的输入参数的简单检查。
我会从您的代码中完全删除 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 = "";
}
我希望这有帮助。
推荐阅读
- git - Intellij Github Integration 给了我一个不同的帐户
- php - Laravel 6 - MariaDB 10.1:Illuminate\Database\QueryException:SQLSTATE[HY000] 迁移错误
- python - matplotlib 阻止我的其余代码运行
- python-3.x - Errno 2 没有这样的文件或目录:'credentials.json'
- java - 如何将复杂的 YAML 解析为 Java 对象层次结构(Spring Boot 配置)
- python - 如何为没有字段的模型制作 Django 夹具?
- c# - unity重新编译序列化脚本
- html - 文本框不应允许在输入字段中键入 1 到 23 以外的数字
- sql - 带有主键的 SQL 中两个连接表的大小
- symfony - Symfony 4 - 我必须使用循环引用服务