c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
JavaScript

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

| | JavaScript

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