What is the role of throw statement in JavaScript?

HTMLJavascriptProgramming Scripts

<p style="">Use the&nbsp;<em>throw</em> statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take appropriate action.</p><h2>Example</h2><p style="">You can try to run the following code to implement throw statement &minus;</p><pre class="prettyprint notranslate" style="">&lt;html&gt; &nbsp; &nbsp;&lt;head&gt; &nbsp; &nbsp; &nbsp; &lt;script&gt; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&lt;!-- &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function myFunc() &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var a = 100; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var b = 0; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;try{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ( b == 0 ){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;throw( &quot;Divide by zero error.&quot; ); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var c = a / b; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;catch ( e ) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(&quot;Error: &quot; + e ); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//--&gt; &nbsp; &nbsp; &nbsp; &lt;/script&gt; &nbsp; &nbsp;&lt;/head&gt; &nbsp; &nbsp;&lt;body&gt; &nbsp; &nbsp; &nbsp; &lt;p&gt;Click the following to see the result:&lt;/p&gt; &nbsp; &nbsp; &nbsp; &lt;form&gt; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&lt;input type = &quot;button&quot; value = &quot;Click Me&quot; onclick = &quot;myFunc();&quot; /&gt; &nbsp; &nbsp; &nbsp; &lt;/form&gt; &nbsp; &nbsp;&lt;/body&gt; &lt;/html&gt;</pre>
raja
Updated on 23-Jun-2020 07:25:09

Advertisements