JavaScript/Reserved words/throw
Appearance
The throw keyword
[edit | edit source]The throw keyword is used to be sure that an exception is caught when it occurs. It has the obligatory catch clause, and the optional finally clause. If the code inside the try block does not cause an exception, the code inside the finally block will execute, if it exists. If an error occurs, the comments inside the catch clause will execute, the finally block will execute, if it exists.
Examples
[edit | edit source] The code
var result;
try {
result = log(-12.05);
alert("Executed comment successfully.");
} catch(err) {
document.getElementById("demo").innerHTML = err.message;
throw("An error occurred, and result could not be calculated!");
} finally {
alert("result = " + result); // This line will execute anyway
}
(An exception with the text "An error occurred, and result could not be calculated!" will be thrown.
result = undefined