5

I'm writing a non-spring aop aspect using aspectJ and I'm writing a before advice for it.

In my before advice, let's say I want to open a file. So I execute it as such:

 public before(): mypointcut() {
    File file = new File("myfile");
    file.getCanonicalPath();
 }

But IntelliJ gripes about IOException being an unhandled exception. How can I write the before advice such that it can either catch and rethrow the exception or allow the unhandled exception?

4

1 回答 1

2

为了将异常提交到调用堆栈,您必须在通知中添加 throws 声明,就像使用普通方法调用一样:

public before() throws IOException: mypointcut() {...}

此建议只能应用于自己声明抛出此异常(或异常的父级)的方法。

为了重新抛出它,您需要捕获异常并在 RuntimeException 实例中重新抛出它,如下所示:

public before(): mypointcut() {
    File file = new File("myfile");
    try {
        file.getCanonicalPath();
    } catch (IOException ex) {
        throw new RuntimeException(e);
    }
}

如果这是一个好主意,那就另当别论了……

于 2013-06-15T17:30:43.993 回答