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:
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:
Which is used like this:
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
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