【问题标题】:Can you throw an exception from a Raw AspectJ Before advice你能从 Raw AspectJ Before 建议中抛出异常吗
【发布时间】:2013-06-16 01:30:43
【问题描述】:

我正在使用 aspectJ 编写一个非弹簧 aop 方面,并且我正在为它编写一个之前的建议。

在我之前的建议中,假设我想打开一个文件。所以我这样执行它:

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

但是 IntelliJ 抱怨 IOException 是一个未处理的异常。如何编写之前的建议,以便它可以捕获并重新抛出异常或允许未处理的异常?

【问题讨论】:

    标签: exception-handling aop aspectj


    【解决方案1】:

    为了将异常提交到调用堆栈,您必须在通知中添加 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);
        }
    }
    

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

    【讨论】:

    • 我知道我的困惑在哪里。我最近才读到 (eclipse.org/aspectj/doc/next/progguide/semantics-advice.html) 建议只能抛出某些类型的异常:运行时就是其中之一。所以你是对的,如果我得到一个异常,我需要将它包装在一个“advice throwable”异常中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    相关资源
    最近更新 更多