X extends Exception

From EggeWiki
Revision as of 08:16, 26 June 2008 by Egge (talk | contribs) (New page: In response to [http://nat.truemesh.com/archives/000738.html Generic Throws: Another Little Java Idiom] Unfortunately, the "X extends Exception" falls apart fairly quickly with the curren...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

In response to Generic Throws: Another Little Java Idiom

Unfortunately, the "X extends Exception" falls apart fairly quickly with the current generation of type erasure. You can get a little way down this path, but soon you'll hit string compile errors, which go away, depending on the order in which you compile / recompile things. The problem is two fold:

  1. Java has type erasure
  2. RuntimeException extends Exception, but doesn't have to be declared in a throws clause.

So, the compiler may or may not be able to determine if a method throws a typed exception.

If this technique worked, it would be useful for implementing closure like features. For example:

<geshi lang="java"> public interface BlockBase<I, O, X extends Throwable> {

   O eval(I item) throws X;

}

   public <X extends Throwable> RArray<T> findAll(BlockBase<T, Boolean, X> block) throws X {
       RArray<T> arr = new RArray<T>();
       for (T t : this) {
           if (block.eval(t)) {
               arr.append(t);
           }
       }
       return arr;
   }

</geshi>

You'll notice in code like fork-join framework, they rely wholly on unchecked exceptions.