0

I'm trying to evaluate a string in Java, using the following code from another answer on the newsgroup.

import java.lang.Object;

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

ScriptEngineManager m = new ScriptEngineManager();

ScriptEngine e = m.getEngineByName("js");

Object result = e.eval("13+23-3");

However, I get an "unreported exception javax.script.ScriptException; myst be caught or declared to be thrown" .. error at compile time. As I am still learning and unfamiliar with exception handling to a great extent, can someone please help me out?

Thanks.

1 Answer 1

4

When a method declares a checked Exception, such a ScriptException, you must either catch and handle it, or declare that your method throws it. In the latter case, every method that calls your method must now catch or declare it, and the chain goes on.

You can catch an exception with the try/catch blocks:

try {
    Object result = e.eval("13+23-3");
    System.out.println("It worked!:" + result.toString());
}
catch (ScriptException se) {
    System.out.println("Problem in eval:", se.getmessage());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.