Benjamin Villalona
Benjamin Villalona

Reputation: 5

how to use a precondition check to stop next line from executing (or for whatever other reason it might be used for)

Like if I had an else if or try catch statement. How can I stop specific lines of code from executing if the statement failed or caught an unhandled exception

I already posted the question before, so I'm just reformulating.

If you don't want the program to execute a certain line of code if the try catch fails, what would you do?

        try
        {
            
            PRECIO = Convert.ToDouble(TBPRECIO.Text);
            CANTIDAD = Convert.ToDouble(TBCANTIDAD.Text);
            CATEGORIA = Convert.ToDouble(TBCATEGORIA.Text);
            
        }



        catch
        {
            MessageBox.Show("NO PUEDE HABER ESPACIOS VACIOS");

            TBPRECIO.Focus();
        }

Upvotes: 0

Views: 162

Answers (1)

IllusiveBrian
IllusiveBrian

Reputation: 3214

I think the general solution to what you're asking is that you can declare a variable outside the try block and set it inside the try block after the line you want to check executes.

bool CANTIDADRead = false;
try
{
    PRECIO = Convert.ToDouble(TBPRECIO.Text);
    CANTIDAD = Convert.ToDouble(TBCANTIDAD.Text);
    CANTIDADRead = true;
    CATEGORIA = Convert.ToDouble(TBCATEGORIA.Text);      
}
catch
{
    MessageBox.Show("NO PUEDE HABER ESPACIOS VACIOS");
    TBPRECIO.Focus();
}
if(CANTIDADRead)
    //do stuff

In your particular case though, you might be better off switching to double.TryParse:

    bool PRECIOREAD = double.TryParse(TBPRECIO.Text, out PRECIO);
    bool CANTIDADREAD = double.TryParse(TBCANTIDAD.Text, out CANTIDAD);
    bool CATEGORIAREAD = double.TryParse(TBCATEGORIA.Text, out CATEGORIA); 

This will attempt to parse the value of those strings and return whether or not the parse is successful. The out keyword means that the variable you pass in will be updated by the method, but if the parse fails it won't be the correct value.

Upvotes: 0

Related Questions