简体   繁体   English

在C#的Try块中,如果要在我的textbock中输入一个int,我想引发异常的catch部分吗?

[英]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.

相关问题 为什么抛出的异常与catch块C#没有正确匹配 - Why thrown exception is not correctly matched with catch block C# 我想实现try and catch异常时重复代码块 - Code block repeating when I want to implement try and catch exception try / catch块中的C#未处理异常,检测到冻结 - C# unhandled exception in try / catch block, detecting a freeze 在C#中检查try / catch块中的异常类型 - Checking for exception type in try/catch block in C# C# .NET:嵌套的 try catch 块未正确处理异常 - C# .NET: nested try catch block not handling exception properly C# 为什么在 try-catch 块内引发异常? - C# Why was exception raised inside try-catch block? 没有try-catch块的C#重新抛出异常 - C# rethrow exception without try-catch block 使用try catch块的C#未处理异常 - C# Unhandled Exception using try catch block 在C#中传播在finally块中抛出的异常而不丢失catch块中的异常的最佳实践是什么? - What is the best practice in C# to propagate an exception thrown in a finally block without losing an exception from a catch block? 在C#中,如果关联的catch块引发异常,是否可以强制控制通过finally块? - in C# is it possible to force control to pass through a finally block if an exception is thrown by an associated catch block?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM