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?
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.
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.
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).
Throwable has two direct subclasses - Exception and Error.
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 {
[...]
}
[...]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With