2

Lets say I am using a third party jar, like HTML parser.
The programmer who wrote that library decided to do printStackTrace();
for handling the exceptions. Few are only warnings. I want to handle them
myself differently in my program.

Is there a way to delegate this without that jar throwing up a stackTrace ?

Shrinath
  • 7,888
  • 13
  • 48
  • 85

3 Answers3

2

You could save references to the initial err and out PrintStreams and then use System.setErr() and/or System.setOut() setting them to some other PrintStream of your choosing.

Tom Micheline
  • 861
  • 1
  • 5
  • 5
0

Don't have a definite answer for you, but I believe it's just not possible. Exceptions are first-caught, first-served, always. So if a .jar has a method that is closer to the exception, and is treating it, there is no way for you to interfere.

You can try to reduce the symptoms, some languages like C will allow you to redirect the stderr stream somewhere else, avoiding the stackTrace printing, and if the exception is rethrown, you could potentially catch it in your code.

Arthur
  • 61
  • 5
  • So to summarize your words, its simply **impossible**... Right ? :( I too think so, but lets see if someone has a "yes" for an answer... – Shrinath Mar 23 '11 at 05:00
0

You can redirect System.err to catch the stack traces.

You can decompile the .jar, and recompile to do something else other than print the stack trace. This is probably the best approach.

The other option is to modify the bytecode on the fly, to rewrite the class at runtime that is printing the stack trace. Depending on how the code that is printing the stack trace is structured, you may be able to use AspectJ or cgilib to make this easier.

sbridges
  • 24,960
  • 4
  • 64
  • 71
  • Lets think about your best approach, how do we do this ? – Shrinath Mar 23 '11 at 05:29
  • Decompile the jar, http://stackoverflow.com/questions/647116/how-to-decompile-a-whole-jar-file then modify the source to do what you want, then compile the modifed source, and use that in place of the jar. I am assuming that you do not already have the source. – sbridges Mar 23 '11 at 05:54
  • Ya, I do not already have the source... If I had it, I wouldn't be here, obviously :D he he :) – Shrinath Mar 23 '11 at 09:40