10

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?

Community
  • 1
  • 1
Steven Roose
  • 2,731
  • 4
  • 29
  • 46

1 Answers1

13

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 {
        [...]
    }

    [...]
}
Community
  • 1
  • 1
reprogrammer
  • 14,298
  • 16
  • 57
  • 93