Forum Stats

  • 3,875,862 Users
  • 2,266,977 Discussions
  • 7,912,357 Comments

Discussions

Unchecked Exception

843810
843810 Member Posts: 46,938
How can I get all of the exceptions Thrown in a java Application?
I Was trying creating a general method called from all the try-catch statemets that can save my program Exceptions, but then I think about the unchecked exception.

Comments

  • 800387
    800387 Member Posts: 5,078
    There is a very easy way to do this: aspect-oriented programming. Here is a sample aspect that will catch any exception that makes it to the service tier whether checked or unchecked that is thrown or not caught:
    @Aspect
    @Component 
    
    public class ErrorHandlingAspect implements Ordered 
    {
        /**
         * Around advice to ensure that errors are handled in a consistent fashion and output
         * in the logs identically for all service methods.  
         * 
         * @param   pjp                         Join point
         * @return  Object                      Invocation result
         * @throws  Throwable
         */
        
        @Around(AopPointcuts.POINTCUT_SERVICE_METHOD)
    
        public Object invokeAround(final ProceedingJoinPoint pjp) 
            throws Throwable 
        {
            try 
            {
                return pjp.proceed();
            }
            catch (Exception e) 
            {
                throw ErrorHandler.handleException(e);
            }
            catch (Error e) 
            {
                ErrorHandler.handleException(e);
                throw e;
            }
        }
    This particular aspect uses Spring AOP. However, that is basically a sub-set of AspectJ. You do a Google to find out how these work. With AOP, you only write one class, and the aspect ensures that any errors are handled by ErrorHandler, which is a custom class that we use to simply log the error appropriately.

    - Saish
  • 843810
    843810 Member Posts: 46,938
    Thanks for the help i will look for the spring aop to see how it looks.
  • 800387
    800387 Member Posts: 5,078
    You are welcome.

    If you are not already using Spring, I highly recommend it. If you choose not to use Spring as a whole, then Spring AOP will obviously not be an option. Use full-blown AspectJ instead.

    Best of luck.

    - Saish
  • jschellSomeoneStoleMyAlias
    jschellSomeoneStoleMyAlias Member Posts: 24,877 Gold Badge
    XxdennixX wrote:
    How can I get all of the exceptions Thrown in a java Application?
    I Was trying creating a general method called from all the try-catch statemets that can save my program Exceptions, but then I think about the unchecked exception.
    catch(Throwable)
This discussion has been closed.