为此,您需要一些AOP框架,该框架将在您的方法周围使用代理。此代理将捕获异常并执行最终块。坦率地说,如果你还没有使用支持AOP的框架,我不确定我会使用一个框架来保存这几行代码。
不过,您可以使用以下模式以更优雅的方式执行此操作:
public void doSomething() {
logAndCleanup(new Callable<Void>() {
public Void call() throws Exception {
implementationOfDoSomething();
return null;
}
});
}
private void logAndCleanup(Callable<Void> callable) {
try {
callable.call();
}
catch (Exception e) {
MyEnv.getLogger().log(e);
}
finally {
genericCleanUpMethod();
}
}
我只是用作接口,但您可以定义自己的接口:Callable<Void>
Command
public interface Command {
public void execute() throws Exception;
}
从而避免了使用泛型并从可调用中返回 null 的需要。Callable<Void>
编辑:如果你想从你的方法返回一些东西,那么使方法通用。下面是一个完整的示例:logAndCleanup()
public class ExceptionHandling {
public String doSomething(final boolean throwException) {
return logAndCleanup(new Callable<String>() {
public String call() throws Exception {
if (throwException) {
throw new Exception("you asked for it");
}
return "hello";
}
});
}
public Integer doSomethingElse() {
return logAndCleanup(new Callable<Integer>() {
public Integer call() throws Exception {
return 42;
}
});
}
private <T> T logAndCleanup(Callable<T> callable) {
try {
return callable.call();
}
catch (Exception e) {
System.out.println("An exception has been thrown: " + e);
throw new RuntimeException(e); // or return null, or whatever you want
}
finally {
System.out.println("doing some cleanup...");
}
}
public static void main(String[] args) {
ExceptionHandling eh = new ExceptionHandling();
System.out.println(eh.doSomething(false));
System.out.println(eh.doSomethingElse());
System.out.println(eh.doSomething(true));
}
}
编辑:使用Java 8,包装的代码可以更漂亮一些:
public String doSomething(final boolean throwException) {
return logAndCleanup(() -> {
if (throwException) {
throw new Exception("you asked for it");
}
return "hello";
});
}