Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture all thrown exceptions in java?

I doubt such a thing is possible, but without attaching a debugger to a java application, is it possible to have some collection populated with information about every exception that is generated in a java application, regardless of if it is caught or not? I know that in .NET, messages get generated by the application about exceptions which at that point are called "First Chance Exceptions", which may or may not subsequently be handled by the application. I'm wondering if there might be a similar mechanism in java I can exploit to view information about all the exceptions generated at runtime.

Just to clarify. This has nothing to do with the context in which an exception occurs. This question is not about what I do in a catch block, or unhandled exceptions. Its about knowing if the JVM provides a mechanism to see every exception generated at runtime, regardless of what generated it, or the context.

like image 561
Mark W Avatar asked Aug 22 '14 16:08

Mark W


1 Answers

Why not, it's of course possible! But firstly.. Logging all exceptions encountered by the JVM is a waste of life. It's meaningless in every sense, there could be several excetion's thrown without any significance.

But if indeed if you have no choice, you could tweak your Java to do that.

Breaking every rule of good programming, what we live for, I give you this idea:

  1. Copy the source code of java.lang.Exception from JDK sources to your project.

  2. Create a method in your Exception.java like below:

    private void logException() {
        // Your logging routine here.
    }
    
  3. Edit java.lang.Exception to call this method logException() at the end of every constructor.

  4. Add the new java.lang.Exception to bootstrap classpath.

  5. Set your logging levels etc and run.

Put your heads up, present this to your weird client, use your diplomatic skills and scare them in few words 'we can do it.. but its your own risk'. Likely you will convince him not to use this.

like image 139
Rajeev Sreedharan Avatar answered Nov 04 '22 09:11

Rajeev Sreedharan