File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes capture printStackTrace even though void Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "capture printStackTrace even though void" Watch "capture printStackTrace even though void" New topic

capture printStackTrace even though void

Stephen Huey
Ranch Hand

Joined: Jul 15, 2003
Posts: 618
I'm getting a NullPointerException but I can't figure out where b/c calling toString on it doesn't tell me that. I figure I need printStackTrace, but that returns void, and I don't know how to access System.out and System.err stuff and print it out on my webpage that my JSP is outputting. I just need to capture the printStackTrace into a string so I can paste it on the webpage and figure out if it's going to tell me a line number in my code.
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
For one of my web apps I've created an "Error.jsp" which is set as the "errorPage" of my other JSPs. Here's a snippet from "Error.jsp" that prints the exception and the StackTrace. You can pass either a PrintStream or PrintWriter to the "printStackTrace()" method, which is what I do here. Then I capture the contents of the writer and dump it to the screen.

The Traceback isn't formatted very nicely (since the browser ignores newline characters), but at least I get what I need.
Hope this helps ...
Stephen Huey
Ranch Hand

Joined: Jul 15, 2003
Posts: 618
Oh, sweet...thanks!
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

If/since you're in a JSP, you could also throw a ServletException wrapped around your exception.
throw new ServletException(myException);
This will print the error on the page in a formatted way (with newlines translated as <br> ) . Note that the first error will be the ServletException; you will want to look beneath that where it will read "Root Cause:" and print out your problem exception there.
[ September 05, 2003: Message edited by: Joel McNary ]

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

You can also wrap a PrintWriter around the JspWriter and pass it directly to e.printStackTrace( new PrintWriter( out ) ), but I tend to use something very similar to Wayne.
You'll be hearing from my lawyers
I agree. Here's the link:
subject: capture printStackTrace even though void
It's not a secret anymore!