React to any exception being thrown

Problem

I would like to react to the event of an exception being thrown. So if someone writes

throw new FooException(); 

the system should notify me such that I am able to react to that event.

I will also accept answers suggesting frameworks or tools that solve this issue, including byte code manipulation.


Details

  • It has to work with any exception; so subclasses of Exception, including RuntimeException. I am not interested in Errors.
  • It has to also trigger for already caught exceptions, no matter where in the code base it happened (including inside the JDK).

So if someone does

try {     foo(); } catch (FooException e) {     ... } 

I want to be able to react to this as well, without modifying the source code of ....

Due to that, a try-catch-em-all around the main-flow does not work, it would not catch already caught exceptions.

Same goes for Thread.setDefaultUncaughtExceptionhandler(...), would not solve the problem.


Please do not suggest to adjust my design or that this might be a XY problem, I am aware and mostly asking because I am curious how to realize this in general.

Add Comment
2 Answer(s)

Aspect Oriented Programming could provide a solution: basically, it allows you to "add" pieces of code (called "advice") at specific locations (called "joinpoints")

For instance, with AspectJ, the code to define an advice that logs each exception thrown by a method call might look like that (I haven’t tried it):

@Aspect class ExceptionMonitoring {      @AfterThrowing(pointcut = "call(* *.*(..))", throwing = "java.lang.Exception")     public void logException(JoinPoint joinpoint, Exception exception) {         System.out.println("The method " + joinpoint.getSignature().getName() + " threw " + exception);     } } 
Add Comment

Not totally sure if that would work, but maybe create the handler as a static method so you could do something like this

ErrorHandler.handle(Class<ExceptionClass> clazz)

and inject that code into every exception class constructor thats available on classpath? You could get the exceptions by scanning the classpath using reflections library, and then try to do bytecode manipulation on those classes using javassist or something similar?

This stuff should be done in some agent library and you need to run your app with this agentlib so the manipulation is done before the actual app starts.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.