How can I unify two catch?

0

We are doing tests to learn how to use exceptions.

    public class Principal {

public static void main(String[] args) {

     int arrayEnterosE[]={1,2,3,0,7};

    try{

        for (int i = 0; i < arrayEnterosE.length; i++) {
        int resultado=0;
        int numero=5;

        resultado=numero/arrayEnterosE[i];
    }

     }catch (Exception e){
         System.out.println("No se puede dividir entre cero");
     }
    try {
        System.out.println(arrayEnterosE[7]);
    } catch (Exception e) {
        System.out.println("Esa posicion no existe en el array");
    } 
    finally    {
    System.out.println("fin de programa");
    }

I tried this:

             try{

        for (int i = 0; i < arrayEnterosE.length; i++) {
        int resultado=0;
        int numero=5;

        resultado=numero/arrayEnterosE[i];
    }

     }catch (Exception e){
         System.out.println("No se puede dividir entre cero");
     }

        System.out.println(arrayEnterosE[7]);
    } catch (Exception e) {
        System.out.println("Esa posicion no existe en el array");
    } 
    finally    {
    System.out.println("fin de programa");
    }

and I get this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
at excepciones.Principal.main(Principal.java:5)
    
asked by David Palanco 09.05.2017 в 14:20
source

4 answers

2

On the basis that you are working, it can not be done. When you exit the block try you can not "open" it again, only the catch and the finally remain.

The best viable option is to make several blocks catch of the same try , capturing more specific exceptions:

try {
  ...
  resultado=numero/arrayEnterosE[i];
  ...
  System.out.println(arrayEnterosE[7]);
} catch (IndexOutOfBoundsException ioe) {
  System.out.println("Esa posicion no existe en el array");
} catch (IllegalArgumentException iae) {
  System.out.println("No se puede dividir entre cero");
}

Of course, when the first exception is thrown inside the block, the execution is interrupted, so only the first exception that occurs is captured (the second one never happens because the code that launches it it does not run).

The alternative of doing only catch of Exception and find out by instanceof its type works, although it is much less common and more difficult to read.

Points to consider:

  • If an exception that you capture is subclassed from the other, the subclass must go before. For example, if you wanted to add a } catch (Exception e) { , you should go to the end of everything. Otherwise, it will give you a compilation error (because the exception will be captured by the most generic block, and the most specific will never be executable.

    } catch (Exception e) {
      // Captura todas las Exception
    } catch (IndexOutOfBoundsException ioobe) {
      // Todas las ioobe ya han sido capturadas por el bloque superior. ERROR
    }
    
  • As of Java 7, you can do the opposite, put two exceptions together in catch

     } catch (IllegalArgumentException | IndexOutOfBoundsException e) {
       ...
     } catch (Exception e) {
       ...
     }
    
  • I understand that it is in an exercise, but exceptions have to be reserved for exceptional situations. If there is a risk of division by zero or access to a nonexistent element, that should be checked before of doing the operation.

answered by 09.05.2017 / 15:00
source
1

A try catch statement serves to execute a piece of code that in some cases may or may not have errors. In case of having errors, we can somehow catch them before the execution of the program ends by not knowing what to do with this error.

The issue of exceptions is a bit long because there are several concepts out there. There are types of errors. The ones you can verify before they happen, the ones you can not verify, and mistakes.

The ones you can check before they occur, for example, are like those in the division by zero, or if you are using files for example, you can infer that maybe the program might not find the file.

Those that you can not verify are errors such as that the index of an array is out of its size, or that for example you refer to something that does not exist.

And the errors are more of the kind that you finish your memory, or that you can not load the main class for some reason.

A try catch is formed mainly of three parts. the try that is part where you are going to put what you want to be executed. The catch that is where the recovery code will be placed in case there is an error. and the finally that is the code that is going to be executed has finished well or badly the code that you put in try .

Of course you can put several catch in the code, to try different types of errors, and depending on this, to enter the catch that corresponds.

This is done as follows.

try{
     int resultado=0;
     int numero=5;
    for (int i = 0; i < arrayEnterosE.length; i++) {

      resultado=numero/arrayEnterosE[i];

    }

}

 }catch (ArithmeticException e){
     System.out.println(e);
 }catch (ArrayIndexOutOfBoundsException e) {
   System.out.println("Esa posicion no existe en el array "+e);
 } finally    {
   System.out.println("LE programa no se pudo terminar con exito :(");
 }

I think there were some errors in your code, I really do not know what you're really trying to do, but tell me anything, and I can help you:)

    
answered by 09.05.2017 в 14:52
1

This is how it is with several catch

 try{

    for (int i = 0; i < arrayEnterosE.length; i++)
    {
        int resultado=0;
        int numero=5;
        resultado=numero/arrayEnterosE[i];            
    }

    System.out.println(arrayEnterosE[7]);

 }
 catch (IllegalArgumentException e)
 {

    System.out.println("No se puede dividir entre cero");
 }        
catch(ArrayIndexOutOfBoundsException e2 )
{
    System.out.println("Esa posicion no existe en el array");
}            
finally
{
    System.out.println("fin de programa");
}

IllegalArgumentException is the exception thrown when trying to divide by zero, and ArrayIndexOutOfBoundsException when you leave the range of the array

    
answered by 09.05.2017 в 14:45
1

You must link them in the same Try, according to your code it would be like this:

    try{

        for (int i = 0; i < arrayEnterosE.length; i++) {
            int resultado=0;
            int numero=5;

            resultado=numero/arrayEnterosE[i];
        }

    }catch (ArithmeticException e){
        System.out.println("No se puede dividir entre cero");
    }catch (IndexOutOfBoundsException a) {
        System.out.println("Esa posicion no existe en el array");
    } finally {
        System.out.println("fin de programa");
    }

    System.out.println(arrayEnterosE[7]);

That's right, notice that in each 'catch' there must be a different exception.

If you want to make the same code for 2 different exceptions and not have to write 2 catch with the same repeated code, do it like this:

    try{

        for (int i = 0; i < arrayEnterosE.length; i++) {
            int resultado=0;
            int numero=5;

            resultado=numero/arrayEnterosE[i];
        }

    }catch (ArithmeticException | IndexOutOfBoundsException e){
        System.out.println("ERRORES...");
    } finally {
        System.out.println("fin de programa");
    }

    System.out.println(arrayEnterosE[7]);
    
answered by 09.05.2017 в 14:39