Unable to catch exception from main in: after () throwing (Exception e) - AspectJ

I am trying to catch the exception that is thrown in my main in my Java class.

My main code is:

public static void main(String[] args){
    new something();
    throw new RuntimeException();
}

In my aspect, I created both after() returning: execution(* main(*)) { advice}, and after() throwing(Exception e): execution(* main(*)) { advice }to find out if the exception was mostly selected or not, to do something different with each advice.

Please note that in the second I print an exception on the output eusing:

System.out.println("Threw an exception: " + e + "Joinpoint: " + thisJoinPoint.getSignature().toString());

The problem is that even if I exclude the exception basically, and I can see from the output that the matching pointcut is second (Ouput:) Threw an exception: java.lang.RuntimeExceptionJoinpoint: void main(String[]) , I still get this error in my output:

Exception in thread "main" java.lang.RuntimeException
    at main(C.java:24)

So, as I understand it, I did not select an exception, I just determined that the exception occurred mainly.

, , around()?

+4
1

after() throwing, around(), .

void around(): execution(* MainClass.main(*)) {
    try {
        proceed();
    } catch (Exception e) {
        //suppress
        System.out.println("Suppressed an exception: " 
            + e + "Joinpoint: " + thisJoinPoint.getSignature().toString());
    }
}

after() throwing , - , , ( , ):

after() throwing(Exception e): execution(* MainClass.main(*)) {
    System.out.println("Threw an exception: " + e + "Joinpoint: " 
        + thisJoinPoint.getSignature().toString());
    throw new RuntimeException("Another exception", e);
}

EDIT. , before(), after() returning, after() throwing after() around() advice, .

void around(): execution(* MainClass.main(*)) {
    try {
        //before() code
        System.out.println("Before main started.");

        proceed();

        //after() returning code
        System.out.println("Main exited normally.");
    } catch (Exception e) {
        //after() throwing code suppressing exception unless you rethrow it
        System.out.println("Suppressed an exception: " + e + "Joinpoint: " 
            + thisJoinPoint.getSignature().toString());
    } finally {
        //after() code
        System.out.println("After main executed.");
    }
}

:

Before main started.
Main started.
Suppressed an exception: java.lang.RuntimeException: errorJoinpoint: void MainClass.main(String[])
After main executed

, after() returning , , , after() returning .

+5

All Articles