Question

package Exception;

public class Exceptions {
    public class NoSpaceException extends RuntimeException {
        public NoSpaceException(){
            super("There is not enough room in the set for another element.");
        }
    }

    public class NotValidTypeException extends NullPointerException {
        public NotValidTypeException(){
            super("You can only add strings to a set.");
        }
    }

    public class NoItemException extends NullPointerException {
        public NoItemException(){
            super("There is no next element.");
        }
    }
}

My other classes don't have visibility for this package. I have three other classes that may throw one of these exceptions, and I don't want to copy/paste the code above sans package declaration onto each file. I'd like to reduce redundancy and have it as a separate file.

How can I make them visible?

Was it helpful?

Solution

Either change the inner classes to be static, i.e.:

public class Exceptions {
    public static class NoSpaceException extends RuntimeException {
        ...
    }

    public static class NotValidTypeException extends RuntimeException {
        ...
    }

    public static class NoItemException extends RuntimeException {
        ...
    }
}

Or, if you don't want to change anything, you can create instances through an instance of Exceptions:

Exceptions exceptions = new Exceptions(); RuntimeException e = exceptions.new NoItemException();

The first approach is preferable.

One more note, consider extending classes that are more specific than RuntimeException (e.g. IllegalArgumentException, IllegalStateExecption, etc).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top