3

I know I can set my own UncaughtExceptionHandler to execute code on uncaught exceptions, but is there a way to have some code execute on all caught exception without having to call that method in every single try-catch block?

My custom code sends me an email with the stack trace on uncaught exceptions. I also want that email for caught exception but I don't want to track down every single try-catch statement and add it.

I'm not looking for a global exception handler (I mentioned UncaughtExceptionHandler), I'm looking for a global CAUGHT exception handler.

RockManX77777
  • 151
  • 1
  • 7

2 Answers2

2

You can do it by altering the Exception class to record every Exception. This can be done by changing the boot class path, runtime code injection or using the JVMTI.

I suspect it's a bad idea as the system will catch more exception than you might expect. You could get thousands of emails a second if something goes wrong.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

I suggest you revisit your exceptions handling policy and strategy. When an exception happens it generally means something went wrong, i.e., something exceptional (as in unexpected) happened in the code (database connection lost, file not found, network unreachable, etc.) or a bug in the code causes an unexpected problem (NPE comes to mind...). In these scenarios the normal program flow can't continue.

It's usually considered best practice to fail fast in such cases, unless you are expecting some exception to be thrown and know how to recover, i.e., the exceptional condition wasn't that exceptional after all.

If you need to fail fast, you don't need to explicitly handle the exceptions as your thread or program will just die and you can just use the UncaughtExceptionHandler to log the stack trace, send emails or notifications etc.

Situation in which you can successfully recover and resume the normal program flow are far less common in my opinion and usually do not require developers/ops to be notified as it is part of the normal functioning of the system (otherwise you would not be able to handle the exception). So simply logging the specific message and useful data associated to this scenario is usually enough, e.g., "WARNING: Transient error x was recovered. State was y and z.".

Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94