Answer the question
In order to leave comments, you need to log in
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;
}
public abstract class Message extends Exception {
public abstract String toString ();
}
public class ArrIsFull extends Message {
public String toString() {
return "Array is full!";
}
}
public class ArrIsEmpty extends Message{
public String toString() {
return "Array is empty!";
}
}
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--]);
}
}
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
At the size of the array, the 10
first 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.length
in the string arr[count++]
will be out of bounds of the array.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question