Why doesn't Java support generic Throwables?

后端 未结 5 1650
独厮守ぢ
独厮守ぢ 2020-12-14 17:02
class Bouncy extends Throwable {     
}
// Error: the generic class Bouncy may not subclass java.lang.Throwable

Why doesn\'t Java

5条回答
  •  自闭症患者
    2020-12-14 17:48

    Here are a couple of things you can do:

    1. Throwables can implement generic interfaces, as long as the throwable itself has no type parameters, e.g.

      interface Bouncy {
          // ...
      }
      class BouncyString extends Exception implements Bouncy {
          // ...
      }

    2. A throws clause can refer to type parameters, e.g.
      static void
      throwIfInstanceOf(Throwable ex, Class clazz) throws X {
          if (clazz.isInstance(ex)) throw clazz.cast(ex);
      }

提交回复
热议问题