Back to: JavaScript Tutorial For Beginners and Professionals
Exception Handling in JavaScript with Examples
In this article, I am going to discuss Exception Handling in JavaScript with Examples. Please read our previous article where we discussed JavaScript Events in detail. At the end of this article, you will understand what is Exception Handling and how to implement Exception Handling in JavaScript with examples.
Note: In programming terms, an exception is an abnormal condition or situation in the code that breaks the normal flow of the code execution.
What is Exception Handling?
Exception Handling is a procedure or mechanism used for handling abnormal statements i.e. the runtime error which occurred during the execution of a program. For example, the Division of a non-zero value with zero is not possible and if we do this in our code, then it will raise an exception during the execution. So, with the help of exception handling, we handle the abnormal conditions i.e. exceptions and give life to our programs. With proper exception handling, if we give a proper exception message to the end-user (the user who uses our application) can take necessary actions.
Exception Handling:
In JavaScript, a throw statement is used to raise an exception. That means when an abnormal condition occurs, an exception is thrown using the throw statement. The thrown exception is handled by wrapping the code into the try…catch block. If an error is present, the catch block will execute, else only the try block statements will get executed. If this is not clear at the moment, then don’t worry we will explain the above points in detail.
Types of Errors in Programming Languages:
While coding, there can be possible three types of errors in the code. They are as follows:
- Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming language, a syntax error appears. This does not harm our application as we came to know this at the time of compiling.
- Runtime Error: When an error occurs during the execution of the program, such types of errors are known as Runtime errors. The codes that throw an error that occurs at runtime are known as Exceptions. Using exception handlers mechanisms i.e. using try-catch block we can handle such types of errors. As a developer, it is your key responsibility to handle such types of errors.
- Logical Error: An error that occurs when there is any logical mistake in the program that may not produce the desired output and may terminate abnormally. Such types of errors are known as Logical errors. These errors occurred due to the poor understanding of the business logic.,
Error Object in JavaScript
When there is an error that occurs at the time of program execution i.e. at runtime, that error is thrown by the throw statement by creating an Error object. So, basically, an Error object is created and thrown automatically by the throw statement when an exception occurred. You can use that Error object as a base for creating custom exceptions i.e. user-defined exceptions. The error object has the following two properties:
- name: This property is used to set or return an error name.
- message: This property is used to return an error message in the form of a string.
In spite of Error is a generic constructor, there are the following standard built-in error types or error constructors beside it:
- EvalError: It creates an instance of an error that occurred in the eval(), which is a global function used for evaluating the js string code.
- InternalError: It creates an instance when the JavaScript engine throws an internal error.
- SyntaxError: It creates an instance of syntax error that may occur while parsing the eval().
- TypeError: It creates an instance of an error When a variable is not a valid type
Exception Handling Statements
You can use the Exception handling mechanism in the following ways in JavaScript.
- throw statements
- try…catch statements
- try…catch…finally statements.
JavaScript try…catch
The try…catch is not only used in JavaScript but also is a commonly used statement in most programming languages. This try-catch statement is basically used to handle the exception that occurred in the code.
JavaScript provides a facility to handle such situations. Such a situation can be handled by using try and catch statements. The executable code is kept inside the try block and in case any exception arises it is thrown using the throw statement which is caught by the catch statement.
Note: It is always a good programming practice whether it is javascript or any other programming language, it is always recommended to keep the code that may cause exceptions or errors within the try…catch blocks.
Let’s discuss the try-catch block in detail and understand the role and responsibility of each statement:
try{} Block:
The code which may cause exceptions or errors needs to be put inside the try block. While executing the code which is placed inside the try block, if any error occurs, it passes the control to the catch{} block, so that that catch can take necessary actions to handle the error. If we don’t handle the error, then the code written within the try block is going to be executed. This is a little confusing while compared to other programming languages. So, once we are into the examples section, then you will get clarity about this.
catch{} Block:
You need to write the code in the catch block which is going to be executed when an error occurred in the try block. That means the error handling code needs to be written within the catch block. The catch block either contains the user-defined exception handler or the built-in handler to handle the error in JavaScript. The point that you need to be remembered, like other programming languages, the catch block executes only when there is an error that occurred in the corresponding try block else the catch block is skipped.
Note: The catch block executes only after the execution of the try block. And one more point that you need to remember is for a given try block, there can be one or more catch blocks in JavaScript.
Syntax to use try-catch in JavaScript:
try { expression; } //code to be written. catch (error) { expression; } // code for handling the error.
Example: Exception Handling in JavaScript
<html> <head> Exception Handling </head> <body> <script> try { var a = ["10", "20", "30", "40", "50", "60", "70"]; //a is an array document.write("<br>" + a); // displays elements of a document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be invoked } catch (e) { document.write("<br>There is error which shows " + e.message); //Handling exception error } </script> </body> </html>
Output:
Example: JavaScript Exception Handling using try-catch
<html> <head> <title>try catch example</title> </head> <body bgcolor=blue text="white"> <h4> Enter Either Value as Zero (0)</h4> Value 1: <input type="text" id="t1"/> <br> Value 2: <input type="text" id="t2"/> <br> Answer: <input type="button" id="b1" value="Hit me" onclick="pp()"> <br> <script> function pp() { var c = parseInt(document.all.t1.value) var d = parseInt(document.all.t2.value) var e = 0 try { if (d == 0) { throw "Divisor is Zero" } if (c == 0) { throw "To be divided is Zero" } } catch (error) { alert(error) } } </script> </body> </html>
Output:
Throw Statement in JavaScript
The throw statements in JavaScript are used for throwing user-defined errors. Using the throw statement, the user can define and throw custom errors i.e. user-defined errors. In this case, when the throw statement is executed i.e. the error is thrown by the throw statement, the statements present after this statement (throw statement) will not be executed. Here, the control will directly move to the catch block.
Note: The exception that is thrown using the throw statement can be a string, number, object, or boolean value.
Syntax of try-catch throw statement:
try { throw exception; // user can define their own exception } catch (error) { expression; } // code for handling exception.
Example: try-catch throw statement in JavaScript
<html> <head> <title>Try catch throw example</title> </head> <body> <script> try { throw new Error('This is the throw statment'); //user-defined throw statement. } catch (e) { document.write(e.message); // This will generate an error message } </script> </body> </html>
Output: This is the throw statement
Example: JavaScript try-catch throw statement
<html> <head> <title>Try catch throw example</title> </head> <body bgcolor=blue text="white"> <h4> Enter Week Day Please </h4> Value 1: <input type="text" id="t1"/> <br> Value 1: <input type="button" id="b1" value="click me" onclick="pp()"/> <br> <script> function pp() { var c = parseInt(document.all.t1.value) try { switch (c) { case 1: throw "Sunday" break case 2: throw "Monday" break case 3: throw "Tuesday" break case 4: throw "Wednesday" break case 5: throw "Thursday" break case 6: throw "Friday" break case 7: throw "Saturday" break default: throw "The real error" } } catch (error) { alert(error) } } </script> </body> </html>
Output:
try…catch…finally statements in JavaScript
In Javascript the finally block is optional but if you put the finally block in your code, then irrespective of the error, this block is going to be executed. That means whether an error has occurred or not, this block is definitely going to be executed after the try block and catch block (if an exception occurred).
Note: If you want to execute some code irrespective of error, then those codes must be placed inside the finally block in JavaScript.
Syntax to use try…catch…finally in JavaScript
try { expression; } catch (error) { expression; } finally { expression; } //Execute the code always irrespective of error
Example: try…catch…finally statements
<html> <head> <title>Try catch finally example</title> </head> <body> <script> try { var a = 10; if (a == 10) document.write("ok"); } catch (Error) { document.write("Error found" + e.message); } finally { document.write("Value of a is 10 "); } </script> </body> </html>
Output: okValue of a is 10
Note: JavaScript Exception solver
In the next article, I am going to explain JavaScript this keyword. Here, in this article, I try to explain Exception Handling in JavaScript with examples. I hope this Exception Handling in JavaScript article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this Exception Handling in the JavaScript article.
Hi,
At the end of Exception Handling, again the link of Javascript Hosting is provided which is of previous chapters. The link of “this” keyword should be there..
Thanks and Regards,
ShriGanesh Singh.
Thanks. We have updated the same.