JavaScript > Error Handling

Error handling in JavaScript

How to handle error in JavaScript?


In case of error in the JavaScript code, we can use error handling mechanism. Error is handled in JavaScript using try and catch block.

   <script>
        function TestFunction() {
            try {
                CallAFunctionThatIsNotDefined();
            }
            catch (e) {
                alert("Oops, an error occurred, sorry! Please try again later." + e);
            }
        }
    </script>

    <input type="button" id="btnTest" onclick="TestFunction()" value="Click me" />

In the above code snippet “CallAFunctionThatIsNotDefined()” has been called inside the try block that doesn’t exists on the page and as a result it will error out. Instead of showing actual error to the end user it’s a good idea to show some custom error like we have written in above code snippet.

OUTPUT

 Views: 5202 | Post Order: 56



Write for us






Hosting Recommendations