पिछले topics में आपने program में आयी Exceptions को handle करना सीखा।  Programing करते समय कई जगह हमें किसी particular condition पर exception generate करनी पड़  जाती है।


JavaScript हमें ये functionality provide करती है कि हम user custom exception generate कर सके। इसके लिए हम throw operator का use करते हैं।


JavaScript में throw statement का use user defined exceptions generate करने के लिए किया जाता है।

JavaScript throw Syntax

throw expression; 

expression वह message / value है जो हमें as a error generate करनी है।

हालाँकि आप JavaScript predefined constructor Error का use करके custom generated error का Object भी बना सकते हैं।

throw new Error("message"); //generates an error object with the message

JavaScript throw Example

File : customerror.html

Copy Fullscreen Close Fullscreen Run
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>JavaScript User Defined Exceptions In Hindi </title>
  </head>
  <body>
    <script type="text/javascript">
      try
      {
        let num = prompt('Enter Any Number : ');
        if(num == 0)
          throw new Error("Invalid number");
        else
          document.write(`You entered : ${num}`);
      } 
      catch(ErrorObj)
      {
        document.write(`Error Name : ${ErrorObj.name} <br>`);  /* print Error name */
        document.write(`Error Message : ${ErrorObj.message}`); /* print Error message */
      }
    </script>
  </body>
</html>
Output
Error Name : Error
Error Message : Invalid number

Where prompt() function window Object का एक function जिसका use user input लेने के लिए किया जाता है। window Object के बारे में हम आगे पढ़ेंगे।

? अगर आप custom exception generate करने के लिए Predefined Constructors use करते Exception generate होने पर हमें Error Object मिलता है , और अगर simple expression / message throw करते हैं तो console में सिर्फ message ही print होता है।

JavaScript में custom Exception generate करने के लिए बहुत से predefined constructors हैं -

  • Error
  • SyntaxError
  • ReferenceError
throw new Error("message");
throw new SyntaxError("message");
throw new ReferenceError("message");

हम जानते है की जब भी program में कोई Exception आती है तो उस error का object बन जाता है जिसकी main property name (error name) और message (error message) होती हैं।

इसलिए Built In construct का use करके generate की गयी Exception का name : constructor name होता है और message जो हम constructor में as a argument pass करते हैं।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers