How to define an interface throwing a generic exception type?

SkyOasis picture SkyOasis · Mar 19, 2012 · Viewed 7.4k times · Source

I wanna define an interface, like

public interface Visitor <ArgType, ResultType, SelfDefinedException> {
     public ResultType visitProgram(Program prog, ArgType arg) throws SelfDefinedException;
     //...
}

during implementation, selfDefinedException varies. (selfDefinedException as a generic undefined for now) Is there a way to do this?

Thanks

Answer

Jon Skeet picture Jon Skeet · Mar 20, 2012

You just need to constrain the exception type to be suitable to be thrown. For example:

interface Visitor<ArgType, ResultType, ExceptionType extends Throwable> {
    ResultType visitProgram(String prog, ArgType arg) throws ExceptionType;
}

Or perhaps:

interface Visitor<ArgType, ResultType, ExceptionType extends Exception> {
    ResultType visitProgram(String prog, ArgType arg) throws ExceptionType;
}