X extends Exception

From EggeWiki

Jump to: navigation, search

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:

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;
    }

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

Personal tools
Travelling Salesman

Get the app!