Exception Handling in JavaScript

Exception Handling in JavaScript

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 the what is Exception Handling and how to implement Exception Handling in JavaScript with examples.

Note: In programming terms, an exception is the abnormal condition or situation in the code that breaks the normal flow of the code execution.

What is Exception Handling?

In programming, exception handling is a process or method used for handling the abnormal statements in the code and executing them. For example, the Division of a non-zero value with zero will result in infinity always, and it is an exception. Thus, with the help of exception handling, it can be executed and handled.

In exception handling:

A throw statement is used to raise an exception. It means when an abnormal condition occurs, an exception is thrown using throw.

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.

In a programming language, there can be different types of errors that may interrupt the proper execution of the program.

Types of Errors

While coding, there can be three types of errors in the code:

  1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming language, a syntax error may appear.
  2. Runtime Error: When an error occurs during the execution of the program, such an error is known as Runtime error. The codes that throws error that occurs at runtime errors are known as Exceptions. Thus, exception handlers are used for handling runtime errors.
  3. 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 an error is known as Logical error.
Error Object in JavaScript

When an error occurs at runtime, it throws an Error object. Such an object can be used as a base for the user-defined exceptions too. An error object has got two properties:

  1. name: It is an object property that sets or returns an error name.
  2. message: This message property returns an error message in the string form.

In spite of Error is a generic constructor, there are following standard built-in error types or error constructors beside it:

  1. 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.
  2. InternalError: It creates an instance when the JavaScript engine throws an internal error.
  3. SyntaxError: It creates an instance of syntax error that may occur while parsing the eval().
  4. TypeError: It creates an instance of an error, When a variable is not a valid type
Exception Handling Statements

There are following statements that handle if any exception occurs:

  • throw statements
  • try…catch statements
  • try…catch…finally statements.
JavaScript try…catch

A try…catch is a commonly used statement in various programming languages. Basically, it is used to handle the error part of the code.

JavaScript provides a facility to handle such situations. Such situation can be handled by using try and catch statements. The executable code is kept inside the try block an in case any exception arises it is thrown using throw statement which is caught by the catch statement.

A good programming approach is to keep the complex code within the try…catch statements.

Let’s discuss each block of statement individually:

try{} statement: Here, the code that going to execute is put in the try block. In case any error occurs, it passes to the catch{} block for taking suitable actions and handle the error. Otherwise, it executes the code written within.

catch{} statement: The code that handles the error is written within the block. This block contains either the user-defined exception handler or the built-in handler. This block executes only when any error that occurred needs to be handled in the try block. else, the catch block is skipped.

Note: catch {} statement executes only after the execution of the try {} statement. Also, one try block can contain one or more catch blocks.

Syntax:
try {
      expression;
     } //code to be written.
catch (error) {
            expression;
     } // code for handling the error.
Example:
<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:

Exception Handling in JavaScript

Example:

<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:

JavaScript Exception Handling

Throw Statement in JavaScript

Throw statements are used for throwing user-defined errors. User can define and throw their own custom errors. Once the throw statement is executed, the statements present after this will not execute. The control will directly pass to the catch block.

The exception can be a string, number, object, or boolean value. With the help of throw statement, users can create their own errors.

Syntax of try catch throw statement:

try {
    throw exception; // user can define their own exception  
}
catch (error) {
    expression;
}  // code for handling exception.

Example:

<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:

<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:

JavaScript Throw Statement Example

try…catch…finally statements in JavaScript

Finally is an optional block of statements that is executed after the execution of try and catch statements. Finally block does not hold for the exception to be thrown. Any exception is thrown or not, finally block code, if present, will always execute. It does not care for the output too.

Therefore, we can also use try/catch/throw/finally keyword together for handling complex code.

Syntax:

try {
       expression;
}
catch (error) {
       expression;
}
finally {
       expression;
} //Execute the code always irrespective of error

Example:

<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

In the next article, I am going to explain the JavaScript Hosting. Here, in this article, I try to explain Exception Handling in JavaScript with examples. I hope this article will helps you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *