JavaScript

How to handle exception in JavaScript (try catch exception handling)?

How to handle exception in JavaScript (try catch exception handling)?, someone asked me to explain?

In this article, I will show you error handling in JavaScript with example. The JavaScript try catch block catches the error throw an exception. Here I used to show JavaScript errors using alert message.

Example:

<script type="text/javascript">
        var txt = "";
        function message() {
            try {
                alret("Welcome user!");
            } catch (err) {
                txt = "There was an error on this page.\n\n";
                txt += "Error description: " + err.description + "\n\n";
                txt += "Click OK to continue.\n\n";
                alert(txt);
            }
        }
    </script>

    <form id="form1" runat="server">
        <div style="border: 1px solid #d2cece; width: 500px; height: 350px; text-align: center">
            <h2>try catch in javaScript</h2>
            <br />
           <a href="#" onclick="message()" target="_blank">click me</a>
        </div>
    </form>

Description:

When the user clicks the “click me” button it calls the JavaScript function, it’s written with try catch exception handling. I want to show alert “welcome user”. But I misspelled it as “alret”. If any occur in the function it will show the error message. Here it shows the error message as “undefined”.

Output:

error handling in javascript try catch example

Post your comments / questions