尝试捕获 - 良好的做​​法?用户在运行时输入

时间:2018-05-21 19:04:56

标签: c# if-statement try-catch user-input textchanged

这个问题建立在我4天前提出的问题上complex if statement in an text changed event。我试了很多,所以问题System.ArgumentOutOfRangeException没有发生。出现问题的原因是if语句在文本更改事件中并检查了8个字符,这些字符在运行时出现。因此,并非所有字符都可立即使用,而是由用户的输入动态生成。这是问题开始的地方,每次文本框中的文本发生更改时,事件都会被触发,同时程序会立即需要8个字符,并在逻辑上给出错误消息System.ArgumentOutOfRangeException。为了解决这个问题,我在try-catch块中添加了if-statement。现在它有效,但这是一个好习惯吗?还有其他/更好的解决方案吗?这是我的代码的摘录:

private void txtBoxEingabe_TextChanged(object sender, EventArgs e)
{
    axAcroPDF1.LoadFile("DONTEXISTS.pdf");

    radioButton1.Visible = false;
    radioButton2.Visible = false;

    string text = txtBoxEingabe.Text.Substring(0, txtBoxEingabe.TextLength);

    try
    {
        if (text.Substring(0, 3) == "SEH" && text.Substring(3, 1) == "M" && Convert.ToInt32(text.Substring(4, 4)) <= 2999 && (text.Substring(8, 1) == "H" || text.Substring(8, 1) == "R"))
        {
            radioButton1.Visible = true;
            radioButton2.Visible = true;

            radioButton1.Text = "1. Document";
            radioButton2.Text = "2. Document";

            this.radioButton1.CheckedChanged += RadioBtnChangedDC1;
            this.radioButton2.CheckedChanged += RadioBtnChangedDC1;
        }
    }
    catch 
    {

    }

private void RadioBtnChangedDC1(object sender, EventArgs e)
{
    if (radioButton1.Checked == true)
    {
        axAcroPDF1.LoadFile("C:\Doc1.pdf");
        axAcroPDF1.gotoFirstPage();
        Screensize = 100;
        axAcroPDF1.setZoom(Screensize);
        axAcroPDF1.setShowScrollbars(true);
        axAcroPDF1.setShowToolbar(false);
    }
    else if (radioButton2.Checked == true)
    {
        axAcroPDF1.LoadFile("C:\Doc2.pdf");
        axAcroPDF1.gotoFirstPage();
        Screensize = 100;
        axAcroPDF1.setZoom(Screensize);
        axAcroPDF1.setShowScrollbars(true);
        axAcroPDF1.setShowToolbar(false);
    }
}

该程序应该是一个显示数百个文档的查看器。

1 个答案:

答案 0 :(得分:1)

这是不好的做法,因为您没有检查错误,而是依赖于异常。

这样做,你不需要尝试/捕捉。

if (txtBoxEingabe.Text.Length < 8)
    return;