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
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.
In Java, there are three methods to print exception information. All of them are present in the Throwable class. Since Throwable is the base class for all exceptions and errors, we can use these three methods on any exception object.
println(): println() method in Java is also used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the start of the next line at the console. The next printing takes place from next line.
The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With