Updated on Kisan Patel
If any error in the javascript code then we need to use error handling mechanism. Error is handled in javscript using try-catch block.
Syntax
try { //code block that may be faulty } catch(err) { //code block that handle error if try block has any error }
Example:
<script type="text/javascript"> try{ undefinedfunction() alert('I guess you do exist') } catch(e){ alert('An error has occurred: ' + e.message) } </script>
In the above code snippet undefinedfunction()
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 of the above program…