0

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();
        }
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • `try..catch` cannot *fail*. It either catches the exception, or lets it go on to the default exception handler for the unhandled exception. Both succeed, so *fail* cannot apply. It's somewhat unclear what you're asking, though, as the code you've posted will handle all exceptions that occur because you're not testing for specific ones, and if an exception is thrown on `PRECIO = Convert.ToDouble(TBPRECIO.Text);`, the next two lines of code will not execute. – Ken White Jul 02 '21 at 03:04
  • **Which** line of code do you not want to execute? And why is an if/else not appropriate? – slugster Jul 02 '21 at 03:08
  • thanks for the clarification, im practically new at this. – Benjamin Villalona Jul 02 '21 at 03:26
  • this is what i not want to be executed SUBTOTAL = CANTIDAD * PRECIO; if (CATEGORIA == 1) { DESCUENTO = SUBTOTAL * 0.20; } else if (CATEGORIA == 2) { DESCUENTO = SUBTOTAL * 0.15; } ITBIS = (SUBTOTAL - DESCUENTO) * 0.16; TOTAL = (SUBTOTAL - DESCUENTO) + ITBIS; – Benjamin Villalona Jul 02 '21 at 03:28

1 Answers1

0

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.

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17