T
T
thatmaniscool2017-06-07 19:36:45
Java
thatmaniscool, 2017-06-07 19:36:45

How to skip a piece of code after throwing an exception in Java?

I will give the following example from an array.
First of all I create an interface with the following parameters..

public interface ShowAllExcemption <T, E extends Exception, F extends Exception> {
    public void AddMemeber (T arg) throws E;
    public void ShowMember () throws F;
}

Then I create an abstract parent class that will issue messages on exceptions
public abstract class Message extends Exception {
  public abstract String toString ();
}

And two successor classes that will issue messages when the array overflows and ... the array goes beyond zero.
public class ArrIsFull extends Message {
  public String toString() {
    return "Array is full!";
  }
}

public class ArrIsEmpty extends Message{
  public String toString() {
    return "Array is empty!";
  }
}

Processed class that will contain the same array.
public class ArrClass implements ShowAllExcemption <Integer, ArrIsFull, ArrIsEmpty>{
  private int [] arr = new int [10];
  private int count = 0;

  public void AddMemeber(Integer arg) throws ArrIsFull {
      if (count > arr.length)
        throw new ArrIsFull();
      else
        arr[count++] = arg;
  }


  public void ShowMember() throws ArrIsEmpty {
      if (count == 0)
        throw new ArrIsEmpty();
      else
        System.out.println(arr[count--]);
    
  }
}

And the actual entry point to the program, but the problem is that it throws only one exception, and does not reach the second one. How to make it so that at the first exception the program skips part of the code and then moves on to the next part of the program?
import java.util.*;

public class MainClass {

  public static void main(String[] args) {
    ArrClass arr = new ArrClass ();
    Random rand = new Random ();

    
    try{
      for (int i=0; i!=7; i++)
       arr.AddMemeber(rand.nextInt(10));
    } catch (Message e){
       System.out.println(e);
    }

    
    try{
      for (int i=0; i!=8; i++)
      arr.ShowMember();
    } catch (Message e){
      System.out.println(e);
    }
  }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2017-06-07
@nirvimel

At the size of the array, the 10first loop for (int i=0; i!=7; i++)passes without throwing an exception, since no overflow has been reached. And the second for (int i=0; i!=8; i++)one selects one more element, as a result, underflow occurs (in Russian, it seems, there is no exact analogue to this word) and an exception flies.
Also, instead if (count > arr.length)of there should be a non-strict condition if (count >= arr.length). Otherwise, when count == arr.lengthin the string arr[count++]will be out of bounds of the array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question