Sunday 30 September 2018

JavaScript: Exception Handling

Exception is an event that disrupts the normal flow of execution. JavaScript provides try...catch...finally statements to handle the exceptions.

Syntax
try{


}catch(exception_object){

}finally{

}

try block contains one (or) more statements followed by at least one catch clause or a finally clause, or both. So you can use try...catch...finally block in any one of the following three forms.

a. try followed by catch
try{

}catch(exception_object){

}

b. try followed by finally
try{

}finally{

}

c. try followed by catch and finally
try{

}catch(exception_object){

}finally{

}

try block
The first step to handle the exception is enclose the error prone code in the try block. A try block must have at least followed by catch or finally block.

catch block
catch block handles the exceptions that are thrown inside the try block.

finally block
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. Finally block mainly used to perform clean up operations. If there is no local catch block to handle the exception, the interpreter first executes the finally block and then jumps to the nearest containing catch clause.

exceptionHandle.html
<!DOCTYPE html>

<html>

<head>
    <title>for in loop Example</title>
</head>

<body>
    <script>
        function factorial(n) {
            if (n < 0) {
                throw new Error("n should be >= 0");
            }

            if (n == 0 || n == 1) return 1;

            return n * factorial(n - 1);
        }

        try {
            factorial(-10);
        } catch (e) {
            document.write(e);
        }
    </script>
</body>

</html>

Open above page in browser, you can able to see following kind of text.

Error: n should be >= 0

Is try statements nested?
Yes, you can embed one try statement in other. If an inner try statement does not have a catch clause, the enclosing try statement's catch clause is entered.

Previous                                                 Next                                                 Home

No comments:

Post a Comment