开发者

how do I force an API to let me handle the exception instead of it printing a stack trace?

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 ?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜