What is the most recommended "Try" or "if"

Asked

Viewed 511 times

2

{   
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        double SalarioBase = 0, Descontos = 0, Vantagens = 0;
        try
        {
            SalarioBase = Convert.ToDouble(textBox1.Text);
            Vantagens = Convert.ToDouble(textBox2.Text);
            Descontos = Convert.ToDouble(textBox3.Text);
        }
        catch
        {
            MessageBox.Show("Valores Invalidos");
            return;
        }
        textBox4.Text = Convert.ToString (( SalarioBase + Vantagens ) - Descontos);
    }
}

What’s the difference between using the if and the try

  • 1

    The two answers answer the question about if and try..catch, but I recommend asking about software architecture - has specific tag here in the OS. In the example of your question the intelligence of your application is on the "screen" or view, and that’s not good practice.

3 answers

21

What’s the difference between using if and Try

Well, they’re very different from each other. if serves to make a conditional flow. try ... catch serves to catch errors (or exceptions, in the correct language) and give these errors the proper treatment.

For example, in your code:

try 
{
    SalarioBase = Convert.ToDouble(textBox1.Text);
    Vantagens = Convert.ToDouble(textBox2.Text);
    Descontos = Convert.ToDouble(textBox3.Text);
}
catch
{
    MessageBox("Valores inválidos");
    return;
}

If there is a conversion error in any of the three fields, your code will go to the catch, i.e., it will print an error message and exit the function.

About the title of your question:

Which one is most recommended

There is no such thing as "most recommended" in this case. Each serves a different purpose, so much so that they can be used together. For example:

try 
{
    if (!Double.TryParse(textBox1.Text, out SalarioBase))
    {
        MessageBox("Salário não está no formato correto.");
    }

    if (!Double.TryParse(textBox2.Text, out Vantagens))
    {
        MessageBox("Vantagens não está no formato correto.");
    }

    if (!Double.TryParse(textBox3.Text, out Descontos))
    {
        MessageBox("Descontos não está no formato correto.");
    }
}
catch
{
    MessageBox("Ocorreu algum erro não previsto.");
    return;
}

13

I wouldn’t use either, or even use the if, but in a different way:

using static System.Console;

public class Program {
    public static void Main(string[] args) {
        var textBox1 = "123.45"; //só para facilitar o teste
        var textBox2 = "10"; //só para facilitar o teste
        var textBox3 = "abc"; //só para facilitar o teste
        double SalarioBase;
        if (!double.TryParse(textBox1, out SalarioBase)) WriteLine("Salario Base foi digitado incorrentamente");
        double Vantagens;
        if (!double.TryParse(textBox2, out Vantagens)) WriteLine("Vantagens foi digitado incorrentamente");
        double Descontos;
        if (!double.TryParse(textBox3, out Descontos)) WriteLine("Descontos foi digitado incorrentamente");
        WriteLine(SalarioBase);
        WriteLine(Vantagens);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

For me exceptions should only be used in exceptional situations (including because is slow), which is not the case. Typed numbers may be wrong and it is quite normal that the conversion is not possible. So I prefer the TryParse().

Can anyone claim that the try-catch can solve all at once, only that usually it is not the desired, in general for each one needs a different treatment. A function could simplify these cases.

If you are using C# 7 you can simplify each block:

//note que não precisa declarar a variável aqui, ela fica disponível no escopo
if (!double.TryParse(textBox1, out var SalarioBase)) { 
    WriteLine("Salario Base foi digitado incorrentamente");
}

Another important detail is not use double for monetary value, prefer decimal that works properly.

0

When you already expect a mistake, I always use the If, because it generates a cleaner code.

Otherwise, opt for the Try catch

  • I don’t know why so many negative votes. It is simple: IF if the error is expected in the program flow, otherwise it is an exception and TRY/CATCH should be used. The Sopt punishes objectivity and who is concise, and it is inhospitable for beginners, who did not understand yet that here escapes the rules of QA.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.