Java Reference
In-Depth Information
11
21 22
31 32 33
The throw Statement
A throw statement is used to throw a user-defined exception. It works similar to the throw
statement in Java. Its syntax is:
throw expression;
In Java, a throw statement throws an object of the Throwable class or one of its
subclasses; the expression must evaluate to a Throwable instance. In Nashorn, a throw
statement can throw a value of any type that may include a number or a string. Nashorn
has few built-in objects that can be used as error objects to be thrown in the throw
statement. Such objects are Error , TypeError , RangeError , SyntaxError , etc.
The following snippet of code shows how to throw a RangeError when empId is not
between 1 and 10000:
var empId = -900;
if (empId <= 0 || empId >= 10000) {
throw new RangeError(
"empId must be between 1 and 10000. Found: " + empId);
}
When you run the code, it will print the stack trace of the error on the standard error.
Like Java, Nashorn lets you handle the errors that are thrown. You will need to use a
try-catch-finally statement to handle the thrown errors, which I will discuss in the
next section.
The try Statement
The try-catch-finally statement in Nashorn works the same way as it works in Java.
The try block contains one or more statements to execute that may throw errors.
If the statements throw an error, the control is transferred to the catch block. Finally,
the statements in the finally block are executed. Like in Java, you can have three
combination of try , catch , and finally blocks: try-catch , try-finally , and
try-catch-finally . Unlike Java, ECMAScript supports only one catch block per try block.
Nashorn supports Mozilla JavaScript 1.4 extension that allows multiple catch block per
try block. The syntax for using the try block is:
/* A try-catch block */
try {
// Statements that may throw errors
}
 
Search WWH ::




Custom Search