0

I am trying to create an error handler that will take an error message and print it to the logging file. Is there a way I can get the massage if I use a try/catch like this?

try{
    //code;
}catch(Exception e){
   Main.error=e.?;
}

I have tried e.getMessage() but it only returns null. Thanks in advance

Sylvyrfysh
  • 1
  • 1
  • 3
  • 2
    An exception doesn't necessarily have to have a message. – Sotirios Delimanolis Dec 08 '13 at 21:15
  • 1
    There a various libraries for logging purposes like java.util.logging or log4j – lwi Dec 08 '13 at 21:17
  • It is [questionable whether you should report the message text of exceptions for exceptions that do not indicate bugs](http://stackoverflow.com/questions/7320080/should-you-report-the-message-text-of-exceptions). – Raedwald Mar 24 '16 at 17:23

3 Answers3

6

From the docs of the Throwable class (Where getMessage() comes from):

Returns: the detail message string of this Throwable instance (which may be null).

Thus a null message is a perfectly legal response from getMessage() and is created whenever the Exception class is instantiated with no arguments.

If by message, you mean the Stack Trace, then Throwable defines a getStackTrace method, which allows you to iterate through the various elements that would be printed in a printStackTrace, from which you can get their string output just using toString()

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
1

You could do something like this:

try{
//code;
}catch(Exception e){
      PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
      writer.println(e.toString());
      writer.close();
}
Baklap4
  • 3,914
  • 2
  • 29
  • 56
0

Did you try to use e.toString()?

Martin Majer
  • 3,274
  • 4
  • 23
  • 36