25

Is there a way to print an exception message in Java without the exception?

When I try the following piece of code:

try {
    // statements
} catch (javax.script.ScriptException ex) {
    System.out.println(ex.getMessage());
}

The output is:

Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException:
missing } after property list (<Unknown source>) in <Unknown source>; 
at line number 1

Is there a way to print the message without the exception information, source and line number information. In other words, the message I would like to print in the output is:

missing } after property list
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
sony
  • 1,557
  • 10
  • 36
  • 50
  • You can parse exception message string to get only those pieces you want – om-nom-nom Mar 30 '13 at 19:46
  • 2
    How about just using println with the message you want to output without the getMessage method? – Kakalokia Mar 30 '13 at 19:50
  • You use `getCause()` to get the inner-most exception and `getMessage()` on that, but I wouldn't guarantee that the line number won't be there. It's a rather unusual usecase, can you tell what you want to do? If you just want to output a user-friendly message for a front-end, you're just gonna have to customize it, if it's meant for devs anyway -- the whole thing is much friendlier. – TC1 Mar 30 '13 at 19:50

3 Answers3

25

The output looks correct to me:

Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1

I think Invalid Javascript code: .. is the start of the exception message.

Normally the stacktrace isn't returned with the message:

try {
    throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
    System.out.println(e.getMessage()); // prints "hu?"
}

So maybe the code you are calling catches an exception and rethrows a ScriptException. In this case maybe e.getCause().getMessage() can help you.

djangofan
  • 28,471
  • 61
  • 196
  • 289
micha
  • 47,774
  • 16
  • 73
  • 80
0

In Java, there are three methods to print an exception information.

1. java.lang.Throwable.printStackTrace() method

e.printStackTrace();

2.toString() method :

catch (Exception e)
        {
            System.out.println(e.toString());
        }

3. java.lang.Throwable.getMessage() method

catch (Exception e)
        {
            System.out.println(e.getMessage());
              
        }
ngg
  • 1,493
  • 19
  • 14
-11
try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}