• Post Reply Bookmark Topic Watch Topic
  • New Topic

Throwable  RSS feed

 
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between the output of Throwable.printStackTrace() and Throwable.getMessage()? When would you use one or the other?
 
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first call will return a stack trace of the program at the time the exception was thrown. This response is a "stack" of strings, read from the bottom up, to show which method called which method called which method, etc., at which point the exception occurred. This kind of output is helpful for understanding the path of the thread that the exception.

getMessage() returns whatever the maker/thrower of the exception put into it. If the exception was not constructed with a message string, then it will be null. The idea is to provide the receiver of the exception with something that might be more helpful, and certainly shorter, than a stack trace.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could have written a small program to check it out for yourself:

 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . or looked in the Documentation.
 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:You could have written a small program to check it out for yourself:



Yes indeed, I have done so, however, I was asking for a second opinion in real use.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jon Camilleri wrote:Yes indeed, I have done so, however, I was asking for a second opinion in real use.

If you want an answer to the question "when would you use one or the other", there is no really general answer to that. It depends on what you need or want in the specific situation.

When debugging, stack traces are very useful, because they tell you exactly where the exception happened and what the sequence of method calls is up to the point where the exception was thrown. So a stack trace helps a lot to track down what the cause of the exception is.

In other circumstances, you just want to know what the error message is and you're not interested in the full stack trace, so then you'd just get the message of the exception. For example, usually you would not want to confront users of your application with a stack trace full of technical information, but just with an error message.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!