Javascript Error को Browser पर display करने के लिए Error Object के साथ try_catch statement का इस्तेमाल करना पड़ता है |
Syntax for try_catch Statement
try{ try_statement }catch(errObj){ catch_statement }
Example for try_catch Statement
try : try Block में error; check करने के लिए javascript का code लिखा जाता है |
catch : Error को handle करने के लिए catch clause के साथ parenthesis(()) में Error Object और Block में Error Object के property के साथ javascript code लिखा जाता है |
Example में try Block के अन्दर लिखे हुए statement में अगर कोई गलत हो तो catch block के statement को display किया जाता है और अगर try block का statement सही हो तो catch block के statement को ignore किया जाता है |
Source Code :Output :<div id="test"></div> <script> try { a == 10 } catch(err) { document.getElementById("test").innerHTML = err.message; } </script>
Click here to get Output
Syntax for try_catch_finally Statement
try{ try_statement }catch(errObj){ catch_statement }finally{ finally_statement }
Example for try_catch_finally Statement
finally : try या catch का code; excute हो या ना हो पर finally block में जो code होता है वो execute होता है |
Source Code :Output :<div id="test"></div> <script> try { } catch(err) { document.getElementById("test").innerHTML = err.message; }finally{ document.write("Hello World"); } </script>
Click here to get Output
throw Statement
throw का इस्तेमाल custom error(exception) create करने के लिए किया जाता है |
Syntax for throw Statement
throw value
Parameter :
value : यहाँ पर error(exception) के रूप में String, Boolean value या number दिया जाता है |
Example for throw Statement
Example में function पर दिया हुआ parameter String है लेकिन parameter पर number न होने के कारण custom error(exception) throw किया जायेगा |
यहाँ पर String को throw किया गया है |
Source Code :Output :<div id="test"></div> <script type="text/javascript"> try{ function func(a) { if (isNaN(a)) { throw new Error("a is not a number"); } return a; } document.getElementById("test").innerHTML = func("Hello"); } catch (err) { document.getElementById("test").innerHTML = err; } </script>
Click here to get Output