我正在使用Java和Mozilla Rhino创建一个游戏引擎,我希望所有错误调用一个函数并向其提供错误消息,如
...
} catch(Exception e) {
Abort(e);
}
...
public void Abort(str) {
System.out.println("Script error in "current_script_name+" line: "+line_number\n\n"+e);
}
对于RhinoException来说这很容易,但是我想为其他人提供相同的东西,比如IOException.
解决方法:
这取决于如何抛出异常,所以我需要猜测.它取决于您用于执行Rhino的优化级别.
我猜测异常是从本机Java代码中抛出的(即,你没有使用throw new Packages.java.io.IOException(“…”)).在这种情况下,您可以使用printStackTrace()来解决它.这是一个小脚本(名为test.jsh.js,您将在堆栈跟踪中看到),您可以在Rhino shell中运行:
try {
// foo does not exist
var stream = new Packages.java.io.FileInputStream("foo");
} catch (e) {
e.rhinoException.printStackTrace();
}
……及其输出:
$java -jar $(cygpath -w /opt/java/rhino/1.7R2/js.jar) -opt -1 test.jsh.js org.mozilla.javascript.WrappedException: Wrapped java.io.FileNotFoundException: foo (The system cannot find the file specified) (test.jsh.js#4) at org.mozilla.javascript.Context.throwAsScriptRuntimeEx(Context.java:1773) at org.mozilla.javascript.MemberBox.newInstance(MemberBox.java:202) at org.mozilla.javascript.NativeJavaClass.constructSpecific(NativeJavaClass.java:281) at org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:200) at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:3377) at script(test.jsh.js:4) at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:2487) at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:164) at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:398) at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3065) at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:175) at org.mozilla.javascript.tools.shell.Main.evaluateScript(Main.java:564) at org.mozilla.javascript.tools.shell.Main.processFileSecure(Main.java:486) at org.mozilla.javascript.tools.shell.Main.processFile(Main.java:452) at org.mozilla.javascript.tools.shell.Main.processSource(Main.java:443) at org.mozilla.javascript.tools.shell.Main.processFiles(Main.java:196) at org.mozilla.javascript.tools.shell.Main$IProxy.run(Main.java:117) at org.mozilla.javascript.Context.call(Context.java:515) at org.mozilla.javascript.ContextFactory.call(ContextFactory.java:507) at org.mozilla.javascript.tools.shell.Main.exec(Main.java:179) at org.mozilla.javascript.tools.shell.Main.main(Main.java:157) Caused by: java.io.FileNotFoundException: foo (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(Unknown Source) at java.io.FileInputStream.(Unknown Source) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.mozilla.javascript.MemberBox.newInstance(MemberBox.java:194) ... 18 more
如果你真的想要使用上面的Abort()函数,你可以解析上面的堆栈跟踪中的相应行;或者,您可以显示整个堆栈跟踪,这可能会更有帮助,具体取决于您要执行的操作.