{"id":1100,"date":"2023-12-17T21:00:00","date_gmt":"2023-12-17T21:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1100"},"modified":"2023-12-20T10:41:28","modified_gmt":"2023-12-20T10:41:28","slug":"try-catch-throw-javascript","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/try-catch-throw-javascript\/","title":{"rendered":"Try Catch and Throw Errors in JavaScript (with code)"},"content":{"rendered":"\n<p>When dealing with some code JavaScript, we encounter several errors that need to be handled or removed. Errors occur for various reasons such as accessing an element out of bounds of the index. We need a proper way to deal with these errors to remove inconsistencies. Javascript throw statements or try-catch statements are some of the techniques that one can use to handle errors. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Try-Catch Block in JavaScript<\/strong><\/h2>\n\n\n\n<p><strong>The try-catch blocks in JavaScript are used to capture the errors and handle them. The try block encloses a piece of code that is doubtful of containing an error. The catch block is used to capture or catch that error to make further operations.<\/strong><\/p>\n\n\n\n<p>This simple mechanism allows developers to handle errors easily. The try block contains the possible problematic code that might cause an error during execution. If an exception occurs, the normal flow of the program is interrupted, and control is transferred to the associated catch block. The catch block contains the code that will be executed if such occurs. <\/p>\n\n\n\n<p>The syntax of a try-catch block is as follows.<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>try {\n  \/\/ code doubted to contain an error goes here\n} \ncatch (error) {\n  \/\/ code to handle the error goes here\n}\n<\/code><\/pre>\n\n\n\n<p>The code within the try block is executed. If there\u2019s no error, the catch block is never executed. But, if there\u2019s an error, the control passes to the catch block. <\/p>\n\n\n\n<p>The catch block also contains a parameter that can be used to further extract error information. The code written in the catch block is executed.\u00a0<\/p>\n\n\n\n<p>Developers can use the information provided by the caught exception to log the error by displaying a user-friendly message as well.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is a JavaScript throw Statement?<\/strong><\/h2>\n\n\n\n<p>The try-catch blocks are used to catch the already-known errors. But, the throw statement is a little different. <\/p>\n\n\n\n<p><strong>Throw statements are used to throw a custom error in JavaScript. When it is executed, the program flow is immediately interrupted, and the control is transferred to the nearest catch block.<\/strong><\/p>\n\n\n\n<p>One can define one\u2019s errors according to particular conditions.\u00a0The syntax is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>throw error_expression;<\/code><\/pre>\n\n\n\n<p>where \u00a0error_expression represents the error that is being thrown by the function. It can be a JavaScript string, number, boolean, or even an object.\u00a0<\/p>\n\n\n\n<p>Let us understand with an example example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/making a function to check conditions and throw error\nfunction checkAge(age){\n    if(age&lt;18){\n        throw new Error(&quot;Not Allowed to Vote!&quot;);\n    }\n    else{\n        console.log(&quot;Allowed to Vote!&quot;)\n    }\n}\n\n\/\/declaring variables to check\nlet age1=15;\nlet age2=22;\n\n\/\/calling the function\ncheckAge(age2);\ncheckAge(age1);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Allowed to Vote!\nERROR!\n\/tmp\/NpMOpjTony.js:4\n        throw new Error(\"Not Allowed to Vote!\");\n        ^\n\nError: Not Allowed to Vote!\n    at checkAge (\/tmp\/NpMOpjTony.js:4:15)\n    at Object.&lt;anonymous&gt; (\/tmp\/NpMOpjTony.js:17:1)\n    at Module._compile (node:internal\/modules\/cjs\/loader:1256:14)\n    at Module._extensions..js (node:internal\/modules\/cjs\/loader:1310:10)\n    at Module.load (node:internal\/modules\/cjs\/loader:1119:32)\n    at Module._load (node:internal\/modules\/cjs\/loader:960:12)\n    at Function.executeUserEntryPoint &#91;as runMain] (node:internal\/modules\/run_main:86:12)\n    at node:internal\/main\/run_main_module:23:47<\/code><\/pre>\n\n\n\n<p>The code shows an error and doesn\u2019t execute. The error occurs because the program is written to throw an error whenever the age is less than 18. But the program is not good enough to catch that error. This error has to be caught. Let us modify the code using the try-catch block using a try-catch block.<\/p>\n\n\n\n<p>So, in the below example, we make use of the try-catch block wherever there\u2019s a certainty of an error occurring:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/making a function to check conditions and throw error\nfunction checkAge(age){\n    if(age&lt;18){\n        throw new Error(&quot;Not Allowed to Vote!&quot;);\n    }\n    else{\n        console.log(&quot;Allowed to Vote!&quot;)\n    }\n}\n\n\/\/declaring variables to check \nlet age1=15;\nlet age2=22;\n\n\/\/calling the function by handling them under try-catch block \ntry{\n    checkAge(age2);\n    checkAge(age1);\n}\ncatch(error){\n    console.log(error.message);\n}<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Allowed to Vote!\nNot Allowed to Vote!\n<\/code><\/pre>\n\n\n\n<p>Now, the code has been executed and gives us the right output. The second age, age2 is less than 18 when passed through the function throws an error that is caught by the catch block. The error message from the throw statement is hence printed.<\/p>\n\n\n\n<p>Let us look into another example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/making a function to check conditions and throw an error\nfunction checkMarks(marks){\n    if(marks&lt;50){\n        throw new Error(&quot;Not Applicable &quot;);\n    }\n    else{\n        console.log(&quot;Applicable &quot;);\n    }\n    console.log(&quot;check print&quot;);\n}\n\n\/\/declaring variables to check \nlet marks1=90;\nlet marks2=43;\n\n\/\/calling the function by handling them under try-catch block \n\/\/also check if the last statement of the function is executed or not\ntry{\n    checkMarks(marks1);\n    checkMarks(marks2);\n}\ncatch(error){\n    console.log(error.message)\n}<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Applicable \ncheck print\nNot Applicable\n<\/code><\/pre>\n\n\n\n<p>So, in this example, We have made a function to check the marks. If the marks are less than 50, an error is given which is caught by the catch block.<strong>\u00a0<\/strong><\/p>\n\n\n\n<p>There is one important thing to observe. When marks greater than 90 are passed through the function, the else statement of the function executes, and the line below the else statement executes because it\u2019s part of the function. But, when marks less than 50 are passed and throw is executed, no statement below the throw statement will execute. Hence, we have got the desired output.<\/p>\n\n\n\n<p>The <a href=\"https:\/\/favtutor.com\/blogs\/java-throw-exception\">throw keyword<\/a> does a similar thing in Java as well. Using it, a developer can communicate that something unexpected has happened, preventing the program from continuing with its normal execution.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>Effective error handling is a critical aspect of JavaScript programming. In this article, we studied the error-handling methods of try-catch and throw statements. By using them for error handling, one can create robust and reliable applications that handle errors. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand error handling in JavaScript using try-catch and how to throw custom errors with throw statement using different examples.<\/p>\n","protected":false},"author":9,"featured_media":1103,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11],"class_list":["post-1100","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1100","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1100"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1100\/revisions"}],"predecessor-version":[{"id":1111,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1100\/revisions\/1111"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1103"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1100"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1100"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1100"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}