This is a calculator App. When I try and compile it comes up with the following message unreported exception javax.script.ScriptException; must be caught or declared to be thrown
I have a feeling it is because the class is set as ActionEvent
. I am a student so I am still learning :)
Any ideas? Thanks
\
You can do the following:
// .. other imports
import javax.script.ScriptException;
// .. the rest of your code
if(source==buteq){
try{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine se = manager.getEngineByName("JavaScript");
Object result = se.eval(createEquasion);
finalAnswer = result.toString();
answer.setText(finalAnswer);
catch(ScriptEngineManager e) {
// handle exception
System.err.println("Error evaluating the script: " + e.getMessage());
}
}
In case you are dealing with any kind of exception outside of the method you can add a throws
declaration on your methods signature:
// .. other imports
import javax.script.ScriptException;
// your method signature
public void actionPerformed (ActionEvent e) throws ScriptException {
// ...
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine se = manager.getEngineByName("JavaScript");
Object result = se.eval(createEquasion);
finalAnswer = result.toString();
answer.setText(finalAnswer);
// ...
This should be it.
In your this actionPerformed
method the line se.eval(createEquasion);
is throwing ScriptException
. you have to handle this Excpetion.
Add below code to complie the class
Object result = null;
try {
result = se.eval(createEquasion);
} catch (ScriptException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (result != null)
finalAnswer = result.toString();
ScriptEngine.html#eval
can throws two Exception
- NullPointerException
- ScriptException
NullPointerException
is RuntimeException so compiler will not force you to handle this.But ScriptException
is checked Exception, so compiler will force you to handle this Exception
either insert the code block into try catch or throw it.
try-catch
block
if(source==buteq){
try{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine se = manager.getEngineByName("JavaScript");
Object result = se.eval(createEquasion);
finalAnswer = result.toString();
answer.setText(finalAnswer);
}catch(ScriptException se){
...
}
}
ScriptException
class declaration -
public class ScriptException extends Exception{...}
Please find more information -
- Checked Exception ScriptException
- ScriptEngine.html#eval(java.lang.String)