0

假设我有下面的代码需要在不修改函数的情况下从匿名函数中抛出异常:

FOO.doSomething(new Transactable(){
 public void run(FOO foo) {
     // How to proxy a exception throw
     // from here, without modifying the class
 }
});

像:

@Override
public void run() throws MyCustomException{
       FOO.doSomething(new Transactable(){
           public void run(FOO foo) {
               // How to proxy a exception throw
               // from here, without modifying the class
           }
        });             
}
4

1 回答 1

2

我怀疑我是否正确理解了这一点,但这是我的镜头。我猜您正试图以某种方式将异常从匿名类中移出并从父方法中抛出:

class ExceptionWrapper {
    public Exception exception;
}

@Override
public void run() throws MyCustomException{
       final ExceptionWrapper ew = new ExceptionWrapper();

       FOO.doSomething(new Transactable(){
           public void run(FOO foo) {
               try {
                   ...
               } catch(MyCustomException ex) {
                   ew.exception = ex;
               }
           }
        });             

        if(ew.exception != null) throw (MyCustomException)ew.exception;
}
于 2012-07-06T10:28:43.423 回答