Search code examples
c#if-statementtry-catchuser-inputtextchanged

Try catch - good practice? User input at run time


This question builds on the question I have asked 4 days ago complex if statement in an text changed event. I tried a lot so that the problem System.ArgumentOutOfRangeException does not occur. The problem arises because the if-statement is in a text changed event and checked 8 characters, that arise at runtime. So, not all characters are immediately available but are generated dynamically by the input of the user. This is where the problem starts, every time the text in the textbox changes, the event is fired and at the same time, the program immediately expects 8 characters and logically gives the error message System.ArgumentOutOfRangeException. To deal with this problem, I have put the hole if-statement in a try-catch block. Now it works, but is this a good practice? Are there other / better solutions? Here's an excerpt from my code:

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);
    }
}

This program should be a viewer that shows hundreds of several documents.


Solution

  • This would be bad practice as you are not checking for the error and are instead relying on an exception.

    Do this instead, and you wan't need a try/catch there.

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