10

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

CrepuscularV
  • 983
  • 3
  • 12
  • 25

4 Answers4

15

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;
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • But you'd want to use a conventional naming convention, right? – Tom Hawtin - tackline Mar 19 '12 at 23:19
  • 1
    @TomHawtin-tackline: Yes, although the convention in Java for naming type parameters isn't as clear as it is in .NET... – Jon Skeet Mar 20 '12 at 06:45
  • @JonSkeet I think there are quite clear: single upper case letter (https://docs.oracle.com/javase/tutorial/java/generics/types.html) But it isn't really satisfying so we don't want to follow them :-) – Juh_ Aug 03 '20 at 12:08
6

Your genericized parameter would need to extend Throwable. Something like this:

public class Weird<K, V, E extends Throwable> {

   public void someMethod(K k, V v) throws E {
      return;
   }
}
Perception
  • 79,279
  • 19
  • 185
  • 195
1

You can do something like

public interface Test<T extends Throwable> {
    void test() throws T;
}

And then, for example

public class TestClass implements Test<RuntimeException> {
    @Override
    public void test() throws RuntimeException {
    }
}

Of course, when you instantiate the class you have to declare the exception that is thrown.

EDIT: Of course, replace Throwable with any of your self defined exceptions that will extend Throwable, Exception or similar.

manub
  • 3,990
  • 2
  • 24
  • 33
-4

If I understand the question, you can throw

Exception

as it is the parent class.

kasavbere
  • 5,873
  • 14
  • 49
  • 72