JS Try … Catch Statement



Try … Catch Statement : Error/Exception Handling in JavaScript

  1. Try..Catch block is used to test code block for errors.
  2. Code to be executed is written inside Try block
  3. Catch block contain Code to be executed whenever error occurs.
  4. 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 :

//

Sample Error Handling Code : Message

Error Message when error occurs in javascript try catch block

Explanation :

  1. We have written JavaScript Code inside head section.
  2. Inside body section we are going to trigger click event.
  3. When we click on the button then it will call JavaScript function message().
  4. message() function will again call messages() function which is undefined.
  5. It will jump into catch block and the error handling code will be executed inside catch block.