Exception class creation and implementation

3

I'm having trouble implementing an Exception class. The explanation of the program is:

  
  • Vector strings must be initialized with "" instead of null. "

  •   
  • The capacity of the vector must be able to be changed by a method.

  •   
  • The class must have a String [] and an int as attributes (object variables).

  •   
  • Create methods 'String at (int i)' and 'void put (int i, String st)', which respectively return the String at position i and change the value of String at position i. >

  •   
  • Each access must be checked and if there is a boundary error, the ArrayIndexOutOfBounds exception should be thrown.

  •   
  • Create a 'int find (String st)' method that returns the position of St in the vector, or -1 if it is not there.

      
  • If a vector is scaled down to a current size, you must first delete the empty Strings ("") and check if the new size contains the remaining Strings. If it does not, you should throw a VectorSizeException exception (create this class).

  •   

The task explained is there, so I just need to know how to implement this exception.

My code:

The Test class (can not be changed):

package Lab4;

public class Teste {

    public static void main( String argc[] ) {
      StringVector v = new StringVector( 10 );

      v.put( 1, "Janeiro ");
      v.put( 2, "fevereiro" );

      System.out.println( v.at( 3 ) );

      System.out.println( v.at( 13 ) ); // Exceção

      System.out.println( v.at(1));

      v.newSize( 2 ); // OK

      v.newSize( 1 ); // Exceção
    }
}

The class StringVector (I've implemented, can be changed):

package Lab4;

public class StringVector {
    String[] vetor;
    int inteiro;

    public StringVector (int vectorCapacity) {
        vetor = new String[vectorCapacity];
        for(int i = 0 ; i < vetor.length ; i++) {
            vetor[i] = "";
        }
    }

    public void newSize (int newSize) {

        String[] novo = new String[ newSize ];

        if (newSize < vetor.length) {
            while(find("") != -1) {
                vetor[find("")] = null;
            }

            /*print pra testar o find e a substituição de valores 
            int i = 0;
            while (i < vetor.length) {
            System.out.println(vetor[i]);
            i++;
            }
            */

            completeVector(novo);

/*          try {
                completeVector(novo);
            } catch (ArrayIndexOutOfBoundsException error) {
                System.out.println("erro: "+ error);
            }*/              
        }
        else {
            completeVector(novo);
        }
    }   

    public String at(int inteiro) {
        try {
            return vetor[inteiro];
        } catch (ArrayIndexOutOfBoundsException error) {
            return "erro: " + error;
        }
    }

    public void put(int inteiro, String st) {
        try {
            vetor[inteiro] = st;
        } catch (ArrayIndexOutOfBoundsException error) {
            System.out.println("erro: " + error);
        }
    }

    public int find(String st) {
        for(int i = 0 ; i < vetor.length ; i++) {
            if(st.equals(vetor[i])) return i;
        }
        return -1;
    }

    public void completeVector (String[] novo) {
        int position = 0;
        for(int i = 0; i < vetor.length ; i++) {
            if(vetor[i] != null ) {
                novo[position] = vetor[i];
                position++;
                /*if(position > newSize) {
                    throw new VectorSizeException();
                }*/
            }   
        } 
    }
}

And my attempt at Exception class:

package Lab4;

public class VectorSizeException extends Exception {

    private static final long serialVersionUID = 1L;

    public VectorSizeException () {
        System.out.println("erro: VectorSizeException");
    }       
}
    
asked by anonymous 30.03.2017 / 18:39

1 answer

6

Well, first (I believe) your implementation of class VectorSizeException is wrong. Syntactically it's perfect, but semantically it does not make much sense. Exceptions should be thrown, in this case you just show the error on the screen. Obviously for your use, which is simple, this can seem extremely useful, since in other cases I can guarantee you that the utility of this is tiny, if not nonexistent.

So, the class VectorSizeException should be this way

public class VectorSizeException extends Exception {

    private static final long serialVersionUID = 1L;

    public VectorSizeException (String message) {
        super(message);
    }
}

Notice that the constructor asks for a string as a parameter and calls the superclass constructor by passing this received argument as a parameter. In the Exception class documentation you can see the definition of this constructor . It is also possible to use the constructor without any parameters, in this case I have kept the parameter to illustrate that an exception can receive a description when it is launched.

Now let's go to the exercise points:

The fifth point says the following

  

Each access must be checked and if there is a boundary error, the ArrayIndexOutOfBounds exception should be thrown.

The methods that make a vector access are at and put . In both methods you make the same mistake, you are capturing an exception, instead launching it, as you request in the exercise. Let's look at the at method:

public String at(int inteiro) {
    try {
        return vetor[inteiro];
    } catch (ArrayIndexOutOfBoundsException error) { 
        return "erro: " + error;
    }
}

The block catch captures the exception that can be thrown if there is an attempt to access a nonexistent index of the array named vetor . The exercise requests that an exception of type ArrayIndexOutOfBoundsException be thrown when improper access occurs.

Of course there are two ways to do this: The first is to let the exception run normally when trying to access an invalid position of the array vetor . For example, an attempt to access the -1 index will cause a ArrayIndexOutOfBoundsException to be released. That is, it is only necessary to attempt an improper access. By illustrating, the method would be

public String at(int inteiro) {        
    return vetor[inteiro];        
}

You can also explicit this (possibly this is what your teacher wants), checking the position you want to access and throwing the exception manually

public String at(int inteiro) { 
    if(inteiro < 0 || inteiro => vetor.length) // qualquer coisa fora de 0 e vetor.length -1 é indevido
        throw new ArrayIndexOutOfBoundsException();

    return vetor[inteiro];        
}

This also applies to the put method.

Now let's go to the last point

  

If a vector is scaled down to a current size, you must first delete the empty Strings ("") and check if the new size contains the remaining Strings. If it does not, you must throw an exception VectorSizeException (create this class).

The class is already created, I'm going to assume that the implementation of the newSize and completeVetor methods are correct and from this point on. Note that exercise says to throw the exception.

I will consider that the verification will be done in the newSize method.

Note that the method signature contains the throws statement, this is because VectorSizeException is a checked-exception (whenever inheriting from Exception will checked >), then you need to add this in the method signature. Therefore, Java forces you to treat this exception at the time you call this method or else add the same statement throws in the method signature to call newSize (in your case, who does this is the method main ).

public void newSize (String[] novo) throws VectorSizeException {
    // Verificar se o novo tamanho é válido
    if(invalido){ // Se o novo tamanho for inválido
        throw new ArrayIndexOutOfBoundsException("Alguma mensagem");
    }        
}

There are some things I said in the answer that may not be clear to you, so I'll leave some references to exceptions here

30.03.2017 / 19:36