JavaScript throw
JavaScript throw statement allows you to create and throw user defined exception. You can use throw statement with try catch statement.
Using JavaScript throw statement, you can completely control program flow and generate the user define error messages.
Syntax
throw expression;
Note JavaScript statements terminated by semicolon, If semicolon not add at the end of statement it effected to automatic semicolon insertion at the end of statements.
There is no line termination between throw keyword and expression in JavaScript.
JavaScript throw with try...catch statement
Example
<script>
var x = 10, y = 5;
try {
if(x == y)
throw "e1";
else
throw "e2";
} catch(e) {
if(e == "e1")
alert("Exception: Both are same value!");
if(e == "e2")
alert("Exception: Both are different!");
}
</script>
In following example we use error constructor to create an Error object. Error object throw exception when errors occur during program execution.
<script>
var x = 10, y = 10;
try {
if(x == y)
throw new Error("Exception: Both are same value!");
else
throw new Error("Exception: Both are different!");
} catch(e) {
alert(e.message);
}
</script>
You can define and initialize new object when you throw an object. Object parameters are assign to a object properties, later that properties reference use in catch block.
In following example create MyObj
object, assign the object properties and use that properties reference in catch block.
<script>
function MyObj(code, message) {
this.code = code;
this.message = message;
}
var x = 10, y = 5;
try {
if(x == y)
throw new MyObj(200, "Exception: Both are same value!");
else
throw new MyObj(201, "Exception: Both are different!");
} catch(e) {
alert(e.code +" : "+ e.message);
}
</script>