Exception handling 您能在通知之前从原始AspectJ抛出异常吗

Exception handling 您能在通知之前从原始AspectJ抛出异常吗,exception-handling,aop,aspectj,Exception Handling,Aop,Aspectj,我正在使用aspectJ编写一个非spring aop方面,并且正在为此编写一个before建议 在我的建议中,假设我想打开一个文件。因此,我这样执行它: public before(): mypointcut() { File file = new File("myfile"); file.getCanonicalPath(); } 但是IntelliJ抱怨IOException是一个未处理的异常。如何编写before通知,使其能够捕获并重新抛出异常或允许未处理的异常?为

我正在使用aspectJ编写一个非spring aop方面,并且正在为此编写一个before建议

在我的建议中,假设我想打开一个文件。因此,我这样执行它:

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

但是IntelliJ抱怨IOException是一个未处理的异常。如何编写before通知,使其能够捕获并重新抛出异常或允许未处理的异常?

为了将异常传递到调用堆栈,必须向通知中添加throws声明,就像普通方法调用一样:

public before() throws IOException: mypointcut() {...}
此建议只能应用于声明自己引发此异常(或异常的父级)的方法

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

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

如果这是一个好主意,那就是另一个故事……

我明白我的困惑所在了。我最近才读到()这篇文章,它指出通知只能抛出某些类型的异常:运行时就是其中之一。所以你是对的,如果我得到一个异常,我需要把它包装成一个“建议可丢弃”的异常。