javagenericsinheritancethrowable

How to restrict that subclass cannot be generic?


Compile time error: The generic class may not subclass java.lang.Throwable

public class TestGenericClass<E> extends Exception {

/*Above line will give compile error, the generic class TestGenericClass<E> may 
  not subclass java.lang.Throwable*/

    public TestGenericClass(String msg) {
        super(msg);
    }
}

Above compile time error is for the reason given in § jls-8.1.2 as below, and explained in this question:

It is a compile-time error if a generic class is a direct or indirect subclass of Throwable(§11.1.1).

This restriction is needed since the catch mechanism of the Java Virtual Machine works only with non-generic classes.

Question:


Solution

  • How it is restricted that subclass of java.lang.Throwable will not be generic class?

    Here's how OpenJDK compiler performs the check:

    import com.sun.tools.javac.code.Symbol.*;   
    
    private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
        ....
    
        // Check that a generic class doesn't extend Throwable
        if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
            log.error(tree.extending.pos(), "generic.throwable");
    

    As you can see forbidden type is kind of harcoded, so you can't use the same technique for your custom class without compiler code customization.

    Full source code