Description:

In this article, I will explain how to do error handling with JavaScript using try and catch statements. 

Error occurs at runtime due to an illegal operation during execution.

try and catch section is used to hide errors from the user and also used to create custom errors.

Inside try section, where you would put any code that might throw an error. It used to test a block of code for errors.

If any error occurs inside the try section, the try section is exited and the catch section is executed.

Catch section is used to handle the errors which are occurred at try section.

The throw statement used to create a custom error and finally section will execute even if the error occurs.

The below example explains how to handle try, catch and finally event using jquery.

Example Program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Exception handling using Jquery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnException').click(function () {
                try {
                    var No1 = 10;
                    var No2 = 0;
                    var divide = No1 / No3; // variable 'No3' throwing error here
                }
                catch (error) {
                    alert(error);
                }
                finally {
                    alert("finally event called");
                }
            });

            $('#btnThrowExcep').click(function () {
                try {
                    var x = 0;
                    if (x == 0) {
                        throw "Value is Empty";
                    }
                }
                catch (error) {
                    alert('Error:' + error);
                }
                finally {
                    alert("finally event called");
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnException" runat="server" Text="Error Handling" />
        <asp:Button ID="btnThrowExcep" runat="server" Text="Throw Exception" />
    </div>
    </form>
</body>
</html>

-

0 comments:

Post a Comment

 
Top