Exception class creation and implementation

Asked

Viewed 998 times

3

I am having problems implementing an Exception class. The explanation of the program is:

  • Vector strings must be initialized with "", not null.

  • The vector capacity shall be capable of being changed by a method.

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

  • Create the 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 the String at position i.

  • Each access must be checked and if there is a limit error, the Arrayindexoutofbounds exception must be launched.

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

  • If an array is resized to a smaller size than the current one, one must first eliminate the empty Strings ("") and verify that the new size holds the remaining Strings. If it does not behave, you must launch a Vectorsizeexception exception (create this class).

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

My code:

To test class (cannot 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 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 to exception class:

package Lab4;

public class VectorSizeException extends Exception {

    private static final long serialVersionUID = 1L;

    public VectorSizeException () {
        System.out.println("erro: VectorSizeException");
    }       
}
  • Can’t do what, specifically?

  • How so? Where should the exception stand?

  • What don’t you know how to do? Cast the exception?

  • Ah, yes. I need to implement the Exception class with that name there. ).

  • Exactly, I don’t know if my exception class is created properly, and I don’t know how to cast

  • I’m making an explanation for you =D

  • thanks, thanks mt :D

Show 2 more comments

1 answer

6


Well, first (I believe) its implementation of the class VectorSizeException is wrong. Syntactically it’s perfect, but semantically it doesn’t make much sense. Exceptions should be thrown, in this case you just show on the screen the error. Obviously for its use, which is simple, this may seem extremely useful, already in other cases I can assure you that the usefulness of this is tiny, if not nonexistent.

So the class VectorSizeException it should be like this

public class VectorSizeException extends Exception {

    private static final long serialVersionUID = 1L;

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

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

Now let’s get to the points of the exercise:

The fifth point reads as follows:

Each access must be checked and if there is a limit error, the Arrayindexoutofbounds exception must be launched.

The methods that make an access to the vector are at and put. In both methods you make the same mistake, you are capturing an exception, rather than launching it, as requested in the exercise. Let’s look at the method at:

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

The block catch catching the exception that can be made if there is an attempt to access a non-existent Internet array called vetor. The exercise asks for an exception of the type ArrayIndexOutOfBoundsException when an improper access occurs.

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

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

You can also spell out this (possibly this is what your teacher wants), checking the position you want to access and launching 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 method put.

Now to the last point

If an array is resized to a smaller size than the current one, one must first eliminate the empty Strings ("") and verify that the new size holds the remaining Strings. If you don’t behave, you must make an exception VectorSizeException (create that class).

The class is already created, I will assume that the implementation of the methods newSize and completeVetor are correct and from this point. Note that exercise says it is necessary launch the exception.

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

Note that the method signature contains the instruction throws, this happens because VectorSizeException is a checked-Exception (whenever he inherits from Exception will be checked), then it is necessary to add this in the method signature. Because of this, Java requires you to treat this exception at the time you call this method or add this same statement to the method throws in the signature of the method you 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 quite clear to you, so I’m going to leave here some references to exceptions

  • In fact it was all absurdly clear! Thank you very much for the attention and the comment! Great hug

Browser other questions tagged

You are not signed in. Login or sign up in order to post.