Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you throw an exception from a Raw AspectJ Before advice

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?

like image 712
Eric Avatar asked Nov 02 '22 20:11

Eric


1 Answers

In order to hand the exception up the call stack you must add a throws declaration to your advice just like with a normal method call:

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

This advice can only be applied on methods that declare throwing this exception (or a parent of the exception) themselves.

In order to rethrow it you need to catch the exception and rethrow it in an instance of RuntimeException like so:

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

If this is a good idea is a another story...

like image 61
shutefan Avatar answered Nov 13 '22 00:11

shutefan