Java Reference
In-Depth Information
print ( cube ( 3 ));
print ( cube2 ( 3 ));
Multiple catch clauses
JavaScript supports try , catch , and throw in a similar way to Java.
JavaScript has no support for checked exceptions—all Java‐
Script exceptions are unchecked.
However, standard JavaScript only allows a single catch clause following a try block.
There is no support for different catch clauses handling different types of excep‐
tion. Fortunately, there is already an existing Mozilla syntax extension to offer this
feature, and Nashorn implements it as well, as shown in this example:
function fnThatMightThrow () {
if ( Math . random () < 0.5 ) {
throw new TypeError ();
} else {
throw new Error ();
try {
fnThatMightThrow ();
} catch ( e if e instanceof TypeError ) {
print ( "Caught TypeError" );
} catch ( e ) {
print ( "Caught some other error" );
Nashorn implements a few other nonstandard syntax extensions (and when we met
scripting mode for jjs we saw some other useful syntax innovations), but these are
likely to be the most familiar and widely used.
Under the Hood
As we have previously discussed, Nashorn works by compiling JavaScript programs
directly to JVM bytecode, and then runs them just like any other class. It is this
functionality that enables, for example, the straightforward representation of Java‐
Script functions as lambda expressions and their easy interoperability.
Let's take a closer look at an earlier example, and see how we're able to use a func‐
tion as an anonymous implementation of a Java interface:
jjs > var clz = Java . type ( "java.util.concurrent.Callable" );
jjs > var obj = new clz ( function () { print ( "Foo" ); } );
Search WWH ::

Custom Search