Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Exception Message in java

Tags:

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 
like image 772
sony Avatar asked Mar 30 '13 19:03

sony


People also ask

How do I print an exception message?

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.

How many ways we can print exception in Java?

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.

What does printing \\ do in Java?

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.

What does e printStackTrace () do?

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.


1 Answers

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.

like image 125
micha Avatar answered Sep 21 '22 13:09

micha