Error while using Script Engine manager to evaluate Java String code

2.2k views Asked by At

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

There are 1 answers

0
jalynn2 On

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());
}