Java Antipattern - Evil rethrow

  • Thread starter Deleted member 43669
  • Start date
Status
Not open for further replies.
D

Deleted member 43669

Guest
Hi all,

I've come across the following situation a lot of times. I call a method that takes a function object, such as:

Code:
public void method(Function a) {
  a.doSomething();
}

...

public interface Function {
  public void doSomething();
}

...

method(new Function() { public void doSomething() {
  // my code here
}});

That is, your typical high-order programming in Java using anonymous classes.

The problem is, if you are in a language with checked exceptions, and the code you want to run inside doSomething() throws a checked exception, it's quite verbose to rethrow the exception "as-is". You could wrap it inside a RuntimeException, but if you really want to behave as if the anonymous class was "transparent", you should unwrap it.

To solve this, I have devised the following:

Code:
public class FakeRuntimeException extends RuntimeException {

	private static final long serialVersionUID = 1L;
	
	public FakeRuntimeException(Throwable t) {
		super(t);
	}
	
	public <R, T extends Throwable> R rethrow(Class<T> type) throws T {
		if(type.isInstance(getCause())) {
			throw ClassUtils.<T>uncheckedCast(getCause());
		}
		return null;
	}

}

Which is used like this:

Code:
try {
  method(new Function() { public void doSomething() {
    try {
    }
    catch(MyException e) {
      throw new FakeRuntimeException(e);
    }
  }});
}
catch(FakeRuntimeException e) {
  return e.rethrow(MyException.class);
}

This is quite concise (as compared to the wrap-unwrap code) and seems to behave correctly.

Thoughts?

(please, leave the checked-exceptions-are-retarded discussion out of this)

Alex
 

Sbodd

Ars Tribunus Militum
1,847
In an odd coincidence, I stumbled across an article about a similar thing yesterday.

How about this (taken from here: http://blog.jayway.com/2010/01/29/sneaky-throw/)

Code:
public class Sneak {
	    public static void sneakyThrow(Throwable t) {
	        if ( t == null ) throw new NullPointerException("t");
	        Sneak.<RuntimeException>sneakyThrow0(t);
	    }
	 
	    @SuppressWarnings("unchecked")
	    private static <T extends Throwable> void sneakyThrow0(Throwable t) throws T {
	        throw (T)t;
	    }
	}

You can then wrap your Function in a SneakyRethrowingFunction similar to what you're doing now, but this way eliminates the need for a FakeRuntimeException class.

(With a few minutes' further thought: the difference with your method is that the rethrow on your end should preserve the checked-ness of the exception for outside code. Which is probably a good thing.)
 
Status
Not open for further replies.