Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was defining a new type of Exception to 'replace' IndexOutOfBounds exception. In first instance I defined a new Class:
Java
public class NoNextItemException extends Exception {
    public NoNextItemException(String message) {
        super(message);
    }

    public NoNextItemException() {
        super("No more elements in the queue");
    }
}

I think you can expect what is this exception for. I implemented the code for the queue like this:
Java
public double peek() throws NoNextItemException {
    if (dataPointer == addPointer) {
        throw new NoNextItemException();

    } else {
        if (dataPointer == cola.length)
            dataPointer = 0;

        return cola[dataPointer];
    }
}

public double next() {
    double value = peek();
    dataPointer++;
    return value;
}


What I have tried:

Now Java raises an error because it's an unhandled exception in next() method. BUT if in NoNextItemException I do inherit from IndexOutOfBoundsException (or simply replace NoNextItemException for it) it doesn't raise any error, so I just have to handle the exception in peek() method.

So, IndexOutOfBoundsException (or any other predefined java exception type) doesn't force you to handle the exception every time you use methods that raises it but Exception does. Why is this due to?
Posted
Updated 10-Feb-23 0:27am

1 solution

Java
public double peek() throws NoNextItemException {

That statement tells Java that the peek method may throw the NoNextItemException. But since this is a Throwable exception, it must be caught in any methods that include a call to peek.

When you inherit from IndexOutOfBoundsException (Java Platform SE 7 )[^], you are telling the system that it is a RuntimeException (Java Platform SE 7 )[^], which is unchecked. And unchecked exceptions are not required to be caught if you are allowing the system to take the default action.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900