Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making the inner class of a generic class extend Throwable [duplicate]

Possible Duplicate:
Why doesn’t Java allow generic subclasses of Throwable?

I'm trying to make a regular RuntimeException inside a generic class like this:

public class SomeGenericClass<SomeType> {

    public class SomeInternalException extends RuntimeException {
        [...]
    }

    [...]
}

This piece of code gives me an error on the word RuntimeException saying The generic class SomeGenericClass<SomeType>.SomeInternalException may not subclass java.lang.Throwable.

What has this RuntimeException to do with my class being generic?

like image 334
Steven Roose Avatar asked Dec 04 '12 01:12

Steven Roose


People also ask

Can we create generic exception by extending throwable class?

A generic class is not allowed to extend the Throwable class directly or indirectly. A method is not allowed to catch an instance of a type parameter.

Can a generic class be extended?

We can add generic type parameters to class methods, static methods, and interfaces. Generic classes can be extended to create subclasses of them, which are also generic.

Can Java inner class be generic?

So you should not declare twice the generic : in the class and its inner class. The E type is indeed visible in the inner class as inner classes have access to other members of the enclosing class (including the generic of the class).

Which of these classes are the direct subclasses of the throwable class?

Throwable has two direct subclasses - Exception and Error.


1 Answers

Java doesn't allow generic subclasses of Throwable. And, a nonstatic inner class is effectively parameterized by the type parameters of its outerclass (See Oracle JDK Bug 5086027). For instance, in your example, instances of your innerclass have types of form SomeGenericClass<T>.SomeInternalException. So, Java doesn't allow the static inner class of a generic class to extend Throwable.

A workaround would be to make SomeInternalException a static inner class. This is because if the innerclass is static its type won't be generic, i.e., SomeGenericClass.SomeInternalException.

public class SomeGenericClass<SomeType> {

    public static class SomeInternalException extends RuntimeException {
        [...]
    }

    [...]
}
like image 156
reprogrammer Avatar answered Oct 27 '22 17:10

reprogrammer