Try … Catch Statement : Error/Exception Handling in JavaScript
- Try..Catch block is used to test code block for errors.
- Code to be executed is written inside Try block
- Catch block contain Code to be executed whenever error occurs.
- JavaScript is case sensitive language so , ’try‘ and ‘catch‘ are written in small case letters.
Syntax : Try..Catch Statement in JavaScript
try { //Run some code here } catch(err) { //Handle errors here }
Live Example : Try..Catch Block Example
<html> <head> <script type="text/javascript"> function message() { try { messages(); } catch(err) { alert(err.message); } } </script> </head> <body> <inputtype="button"value="View message"onclick="message()"/> </body> </html>
Output :
%MINIFYHTML7f5ff0485a16aed569184d19458e230f9%
Sample Error Handling Code : Message
Explanation :
- We have written JavaScript Code inside head section.
- Inside body section we are going to trigger click event.
- When we click on the button then it will call JavaScript function message().
- message() function will again call messages() function which is undefined.
- It will jump into catch block and the error handling code will be executed inside catch block.