Throw Statement in JavaScript : Create an Exception

February 2, 2025 No Comments » Hits : 322





Throw Statement in JavaScript : Create an Exception

  1. Throw Statement in JavaScript allows user to create exception.
  2. If we use throw statement along with try…catch block then we can control whole execution of the program.
  3. The throw statement allows you to throw an error details to the browser’s error console , halting further execution of the script.

Syntax : Throw Statement

throw exception

Live Example :

<html>
<body>
<script type="text/javascript">
var x = prompt("Enter a marks : ","");
try
{
if(x < 40)
  {
  throw "Err1";
  }
else if(x > 100)
  {
  throw "Err2";
  }
  document.write("Student Passed");
}
catch(err)
{
if(err=="Err1")
  {
  document.write("Student Failed");
  }
if(err=="Err2")
  {
  document.write("Invalid Marks");
  }
}
</script>
</body>
</html>

Output :

Step 1 : 
Step 2 : Invalid Marks (If entered marks = 567)

Error Object in JavaScript :

var Err1 = new Error();
Err1.name    = 'My Error Name';
Err1.message = 'Input must be a number Less than 10';
throw "Err1";

Incoming search terms: