Try … Catch Statement in JavaScript : Error Handling in JavaScript

February 1, 2025 No Comments » Hits : 308





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 :

%MINIFYHTML7f5ff0485a16aed569184d19458e230f9%

Sample Error Handling Code : Message

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.

Incoming search terms: