简体   繁体   中英

JAVA aop @AfterThrowing couldn't catch Exception

I want to do some action when this method has an exception. Therefore I made aop function like AfterReturning, AfterThrowing...

I changed the method raising exception on purpose. But the request arrives AfterReturning, not AfterThrowing even if exception is occured.

How can I make this request reach to AfterThrowing method?

    @EventListener
    @GetHost
    public void getHost(ContextRefreshedEvent event) throws Exception {

        try {
            prHostName = InetAddress.getLocalHost().getHostName();
            prIpAddr = InetAddress.getLocalHost().getHostAddress();

            //making exception on purpose
            String[] tmp = new String[0];
            prIpAddr = tmp[1];


        } catch (Exception exception) {
            prHostName = "unknown";
            prIpAddr = "unknown";
            System.out.println("unknown");
            exception.printStackTrace();

        }
    }

There are aop methods

    @Pointcut("@annotation(com.etc.web.annotation.GetHost)")
    public void componentMethod() {}

    @Before("componentMethod()")
    public void beforeComponent(JoinPoint point) {
        System.out.println("beforeComponent");

    }

    @Around("componentMethod()")
    public Object aroundComponent(ProceedingJoinPoint point) throws Throwable {

        System.out.println("aroundComponent");
        Object retVal = point.proceed();

        return retVal;
    }
    @AfterReturning(pointcut = "componentMethod()", returning = "result")
    public void afterComponent(JoinPoint point, Object result) {
        System.out.println("afterReturnComponent");

    }

    @AfterThrowing(pointcut = "componentMethod()", throwing = "exception")
    public void afterThrowingComponent(JoinPoint point, Throwable exception) throws Exception {
        System.out.println("afterThrowingComponent");

       
    }

Please help me. Thanks!

The method does not exit with an exception, because the exception is caught and the method exits normally. So of course, @AfterThrowing is not triggered. That should not surprise you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM