首页 > 解决方案 > 在 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)
        {

        }   
    }

非常小的学校项目,但想指定例外。

标签: c#

解决方案


最好的方法是实现 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 = "";  

    }

我希望这有帮助。


推荐阅读