Introduction to Javascript Throw Exception
When a javascript statement generates an error, it is said to throw an exception. The throw statement throws an error. When an error occurs, javascript will stop and generate an error message which means javascript throwing an error whereas throw statement allows users to create a customized error which means throwing an exception. These exceptions can be javascript string, a Boolean, a number or an object. On using try and catch statements along with throw, the user can control the program flow and generate custom error messages.
Syntax:
throw <expression>;
The expression is the required exception which has to be thrown, can be a string, number, a Boolean or an object.
Generally, errors are thrown by a runtime engine and exceptions are thrown by the developer. In javascript, all exceptions are similar to objects. There are 2 ways to throw an exception, directly with an error object and through the custom object.
Generic exceptions need an exception object to instantiate with an error message as the first parameter of the constructor and then throw whereas custom exceptions allow automatic stack trace in exception response to review the exception thrown.
Examples of Javascript Throw Exception
Below are the examples of throw exception:
Example #1
Code:
<!DOCTYPE html>
<html>
<body>
<p>Please enter a number:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "is not a number";
if(x > 100) throw "is too high";
if(x < 50) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
}
</script>
</body>
</html>
Output:
Without entering any number:
On entering a number below 50:
On entering a non-digit value:
On entering a number greater than 100:
Working of the throw Statement
The throw keyword is used to throw an exception from within a method, whenever a throw statement gets encountered, gets executed. The execution of the current method is stopped and returned to the caller. It allows users to create and throw user-defined exceptions/ error messages. Also, the user can use throw statements along with try and catch statements.
There is no line termination between the statement throw and the expression.
Example #2
Code:
<!DOCTYPE html>
<head>
<title>Throw Statement in JavaScript</title>
</head>
<body>
<script>
var x = 7, y = 7;
try {
if(x == y)
throw "e1";
else
throw "e2";
} catch(e) {
if(e == "e1")
document.write("Both are same value!");
if(e == "e2")
document.write("Both are different!");
}
</script>
</body>
</html>
Output:
If x = 7 and y = 9
Using an error constructor to create an error object, these error objects throw an exception when an error occurs during program execution.
Let us modify the above example using error object,
Example #3
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Throw Statement with Error constructor</title>
</head>
<body>
<script>
var x = 15, y = 10;
try {
if(x == y)
throw new Error("Both are same value!");
else
throw new Error("Both are different!");
} catch(e) {
document.write(e.message);
}
</script>
</body>
</html>
Output:
new Error is the error constructor creating an error object.
Users can also define and initialize a new object when throwing an object, object properties are assigned to object parameters.
In the below example, sampleObj is the object created, will assign the required object properties and use the reference in a catch block.
Example #4
Code:
<!DOCTYPE html>
<head>
<title>Throw Statement with Error constructor</title>
</head>
<body>
<script>
function sampleObj(errorcode, message) {
this.errorcode = errorcode;
this.message = message;
}
var x = 110, y = 54;
try {
if(x == y)
throw new sampleObj(200, "Both are same value!");
else
throw new sampleObj(201, "Both are different!");
} catch(e) {
document.write(e.errorcode +" : "+ e.message);
}
</script>
</body>
</html>
Output:
Let us look at the core concept of using throw statement i.e Exception handling
In Exception handling, we group many statements that are tightly coupled and if one of the statements causes an error while executing, we have to stop at the statement which has caused an error, instead, we use throw statements by checking the conditions where and when the statements can fail.
First, we need to find the problem and throw an exception, and second, we need to catch these exceptions.
Try-Catch-finally block:
Try statement is the block of code that allows testing the code and where exception occurs and these exceptions are thrown using the throw statement. The catch statement handles the errors if any thrown by the throw statement. Finally lets the user execute the code.
Some of the Error Constructors
Basically, Error is the general constructor for errors, others are sub constructors.
- RangeError: Indicated a numeric value exceeding the range which is said to be allowed.
- SyntaxError: Indicates parse error
- ReferenceError: Indicates invalid reference value
- TypeError: Indicated actual type of operand is different from the expected operand
Stack Trace: Sometimes, we face some exceptions that are not expected and to debug these errors, we often need a debugger that can debug the issues, instead we can try manual debugging using this trace of error occurred. With this stack trace, we can get to know the number of the line where the error or exception occurred and the data that is causing, what values are being passed with what data.
Conclusion
The exact definition of throw statement used for handling exceptions along with some examples. Also checked out on how the throw statement works in a program, also learned try-catch-finally block which is used to handle the exceptions thrown by the throw statement. We were able to define some custom exceptions in the examples and had an overview of the errors which we handle on daily programming along with stack trace which is used to debug the errors thrown.