0

我的项目中有以下代码片段,一切正常。我试图将 PropertyVetoException 传播回调用者。删除 try-catch 块并写入public void actionPerformed(ActionEvent e)throws PropertyVetoException 会导致编译错误。为什么会这样。?如何将异常传播回调用者。我知道事件生成方法不是“调用者”,但我想将异常传播到此事件生成方法,指示发生了异常并采取纠正措施。

  public void actionPerformed(ActionEvent e) {
     if(CMD_CHILD.equalsIgnoreCase(e.getActionCommand())) {
          if(child.getTitle().equalsIgnoreCase(title)) {
              try {
                 child.setSelected(true);
              } catch (PropertyVetoException e1) {
                 e1.printStackTrace();
              }
           }
       }
   }
4

2 回答 2

4

Because actionPerformed is specified by the ActionListener interface, and in that interface, there's no throws to indicate that the method might throw any checked exceptions.

When overriding a method from a superclass or implementing a method from an interface, the overriding or implementing method cannot throw any more exceptions than what was specified in the superclass or interface.

Besides that, why would you want to do that? actionPerformed is called by the Swing GUI framework, what would you expect Swing to do with the exception?

于 2013-09-17T07:11:32.050 回答
4

The interface you are implementing (ActionListener) does not declare an exception to the method actionPerformed. You can't change the method signature in your implementation class of that interface.

If you want to throw the exception to the event producer, then you can convert it to a RuntimeException which needs not to be declared in the method signature.

} catch (PropertyVetoEception e1) {
    throw new RuntimeException(e1);
}

Of course, RuntimeException is a little bit generic, you might define your own, application specific exception, such as:

public class EventExecutionException extends RuntimeException {
    ...
}
于 2013-09-17T07:11:59.720 回答