Prevent continuing program when an exception occurs

0

I have this method, which opens an excel file, what I try is that when the route is not correct I can not continue the program until the connection is correct.

    private void Conectar()
            {
                try
                {
                    sheet = excel.Workbooks.Open(tbxRuta.Text);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Fallo al abrir el archivo...", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }

            }

What would be convenient to carry out the program correctly?

    
asked by Edulon 16.11.2017 в 09:10
source

2 answers

1

The method should return information indicating whether the operation has been successful or not so that the logic of the program can decide whether to continue or not.

Something like this:

private bool Conectar(){
  try{
    sheet = excel.Workbooks.Open(tbxRuta.Text);
    return true;
  }
  catch(Exception e){
    MessageBox.Show(e.Message, "Fallo al abrir el archivo...", MessageBoxButtons.OK, MessageBoxIcon.Error);
    return false;
  }
}

This way in the logic of the program you could check if the file has been opened correctly or not:

if (Conectar()){
   // Continuar con el programa
}
    
answered by 16.11.2017 в 09:19
1

You can also check the route before calling the method, for example:

if (File.Exists(tbxRuta.text))
{
    // llamas al método 
}
else
{
    // avisas al usuario que el archivo no existe
}

Even so, it could be the case that the file is not opened for x reasons, it would be another validation if you want to do it.

    
answered by 16.11.2017 в 16:40