throw Statements

By: Dusty Arlia
Published on Monday, April 15, 2013, 07:30 AM
Last Updated on Thursday, July 16, 2015 at 10:30 PM
Total Updates: 5

JavaScript throw statements are used when you need to throw an exception based on a condition. Here is the basic syntax of a throw statement:

throw [expression];

After the keyword throw, you have an expression. This expression can evaluate to any value, of any data type. You might want to throw an error code, which may be a number data type. Or you might want to throw an error message, which would be a string data type.

When the JavaScript interpreter throws a runtime error, it uses the Error class and its subclasses.

Here is a real example:

if (x < 0) throw new Error("x must not be negative");

In the above example, the throw statement executes based on the if condition that proceeds it. If the condition evaluates to true, an Error object is created.

Some exceptions are automatically thrown by the JavaScript interpreter, like runtime errors. These do not require you to write throw statements into your JavaScript program.

When an exception is thrown, the JavaScript interpreter will stop running the program and jump to the nearest exception handler (exception handlers are the catch clause of the try/catch/finally statement). The JavaScript interpreter first looks for a catch clause in the block of code where the exception was thrown. If there is no exception handler in that block of code, the JavaScript interpreter looks at the next highest enclosing block of code. This repeats until an exception handler is found. If an exception was thrown in a function with no try/catch/finally statement, then the JavaScript interpreter must look at the code that invoked the funciton. Exceptions propagate up the call stack looking for an exception handler.

If an exception handler is never found, then the exception is treated as an error and is reported to the user.

Here is an example of a throw statement inside of the try block of a try/catch/finally statement:

var full_name = 1234;

try {
    if (full_name != NaN) throw ("Please do not enter a number for a name");
} catch (new_error) {
    alert(new_error);
} finally {
    full_name = "";
}

Comments:

Ad: