sqlBugs
sqlBugs

Reputation: 115

Globally Log Catch Exception e

Suppose that I have a legacy java application with thousands of lines of code which do:

try {
   // stuff 
} catch (Exception e) {
   // eat the exception
}

Is there any global option that I could flip or 3rd party JAR which would log all "eaten" exceptions? I know that I could do a massive find replace (search for catch (Exception e) { and replace it with catch(Exception e) { logException(e);) but I was wondering if there was a better solution. Thanks!

Upvotes: 10

Views: 506

Answers (4)

aioobe
aioobe

Reputation: 421170

You could perhaps provide your own implementation of Exception which logs the stack-trace in the constructor. From the man page of java:

-Xbootclasspath:bootclasspath
Specify a colon-separated list of directories, JAR archives, and ZIP archives to search for boot class files. These are used in place of the boot class files included in the Java 2 SDK.

Upvotes: 7

Rob Di Marco
Rob Di Marco

Reputation: 44962

Seems like a place where Aspect Oriented Programming could come in handy. You could set up an exception handler pointcut. Check out AspectJ for a nice AOP implementation.

Upvotes: 5

Michael
Michael

Reputation: 35351

This will allow you to handle any uncaught exceptions:

Thread.setDefaultUncaughtExceptionHandler(
  new Thread.UncaughtExceptionHandler(){
    public void uncaughtException(Thread t, Throwable e) {
      //handle the exception
    }
});

Upvotes: 0

Michael Myers
Michael Myers

Reputation: 192015

No. If the code catches the exception and does nothing with it, then there's nothing you can do to change that without changing the code.

A find-replace should work. However, I would also strongly recommend checking it with FindBugs afterward to make sure that you found all instances of this problem. (FindBugs should be a part of your process anyway, but I'm just pointing it out in case anyone who reads this doesn't already use it.)

Upvotes: 0

Related Questions