I saw a question on Stack Overflow asking for a review of a custom try...catch construct that made use of Optional
s, and got the idea to try writing my own version. Mine doesn't use Optional
s though. Each supplied catch
handler is expected to return a value.
I realized about half way through writing this that this is probably an awful idea that should never be used d in the real world for various reasons. I haven't written Java in a few years though, and I'm curious what can be improved.
Example of use:
Integer i =
new Try<>(()-> Integer.parseInt("f"))
.catching(NumberFormatException.class, (e)-> 2)
.catching(IllegalStateException.class, (e) -> 3)
.andFinally(()-> System.out.println("Finally!"));
// Finally!
Integer j =
new Try<>(()-> Integer.parseInt("1"))
.catching(NumberFormatException.class, (e) -> 2)
.execute();
System.out.println(i); // 2
System.out.println(j); // 1
Basically how it works is the Try
object can have catching
methods chained on it that register handlers. When an exception is thrown, it looks for a corresponding handler, and calls it, returning the returned value. If no handler is found, it rethrows the exception.
Major problems:
The need for
.class
is unfortunate. I couldn't think of how else to have the caller indicate the class of exception to be caught though.Non-exception classes can be registered, although it will have no effect other than the minimal memory and CPU usage.
The need for
execute
whenandFinally
isn't used. I can't see how the class would know that allcatch
es have been added though.The need for
new
is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something likeTry.tryMethod
to reference it, which isn't a whole lot better.The check in
andFinally
seems like it's unnecessary. Unless someone does something bizarre like:Try t = new Try<>(() -> null); t.andFinally(() -> {}); t.andFinally(() -> {});
It shouldn't be possible to add multiple
finally
blocks. I'm not sure to what extent I should stop the user from doing stupid things. I could make the object immutable, but again, I'm not sure if that's necessary.
Since this is basically just exercise code, I'd love to anything at all that could be improved here. This is the first Java I've really written in a few years, so I'm sure there's lots that can be improved.
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class Try<T> {
private Supplier<T> tryExpr;
private Map<Class, Function<Exception, T>> handlers = new HashMap<>();
private Runnable finallyExpr;
public Try(Supplier<T> tryExpr) {
this.tryExpr = tryExpr;
}
public Try<T> catching(Class ex, Function<Exception, T> handler) {
if(handlers.containsKey(ex)) {
throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");
} else {
handlers.put(ex, handler);
return this;
}
}
public T execute() {
try {
return tryExpr.get();
} catch (Exception e) {
if(handlers.containsKey(e.getClass())) {
Function<Exception, T> handler = handlers.get(e.getClass());
return handler.apply(e);
} else {
throw e;
}
} finally {
if(finallyExpr != null) {
finallyExpr.run();
}
}
}
public T andFinally (Runnable newFinallyExpr) {
if (finallyExpr == null) {
finallyExpr = newFinallyExpr;
} else {
throw new IllegalStateException("Cannot have multiple finally expressions");
}
return execute();
}
}