{"id":1245,"date":"2022-02-26T06:42:30","date_gmt":"2022-02-26T06:42:30","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1245"},"modified":"2022-02-26T06:42:30","modified_gmt":"2022-02-26T06:42:30","slug":"try-catch","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/26\/try-catch\/","title":{"rendered":"Try&#8230;catch"},"content":{"rendered":"\n<p>In this tutorial, we will learn about the try catch statement in Java with the help of examples.<\/p>\n\n\n\n<p id=\"introduction\">The&nbsp;<code>try...catch<\/code>&nbsp;block in Java is used to handle exceptions and prevents the abnormal termination of the program.<\/p>\n\n\n\n<p>Here&#8217;s the syntax of a&nbsp;<code>try...catch<\/code>&nbsp;block in Java.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try{\n  \/\/ code\n}\ncatch(exception) {\n  \/\/ code\n}<\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>try<\/code>&nbsp;block includes the code that might generate an exception.<\/p>\n\n\n\n<p>The&nbsp;<code>catch<\/code>&nbsp;block includes the code that is executed when there occurs an exception inside the&nbsp;<code>try<\/code>&nbsp;block.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"example\">Example: Java try&#8230;catch block<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n\n    try {\n      int divideByZero = 5 \/ 0;\n      System.out.println(\"Rest of code in try block\");\n    }\n\n    catch (ArithmeticException e) {\n      System.out.println(\"ArithmeticException =&gt; \" + e.getMessage());\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>ArithmeticException =&gt; \/ by zero<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, notice the line,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int divideByZero = 5 \/ 0;<\/code><\/pre>\n\n\n\n<p>Here, we are trying to divide a number by&nbsp;<strong>zero<\/strong>. In this case, an exception occurs. Hence, we have enclosed this code inside the&nbsp;<code>try<\/code>&nbsp;block.<\/p>\n\n\n\n<p>When the program encounters this code,&nbsp;<code>ArithmeticException<\/code>&nbsp;occurs. And, the exception is caught by the&nbsp;<code>catch<\/code>&nbsp;block and executes the code inside the&nbsp;<code>catch<\/code>&nbsp;block.<\/p>\n\n\n\n<p>The&nbsp;<code>catch<\/code>&nbsp;block is only executed if there exists an exception inside the&nbsp;<code>try<\/code>&nbsp;block.<\/p>\n\n\n\n<p><strong>Note<\/strong>: In Java, we can use a&nbsp;<code>try<\/code>&nbsp;block without a&nbsp;<code>catch<\/code>&nbsp;block. However, we cannot use a&nbsp;<code>catch<\/code>&nbsp;block without a&nbsp;<code>try<\/code>&nbsp;block.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"try-finally\">Java try&#8230;finally block<\/h2>\n\n\n\n<p>We can also use the&nbsp;<code>try<\/code>&nbsp;block along with a finally block.<\/p>\n\n\n\n<p>In this case, the finally block is always executed whether there is an exception inside the try block or not.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Java try&#8230;finally block<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void main(String&#91;] args) {\n    try {\n      int divideByZero = 5 \/ 0;\n    }\n\n    finally {\n      System.out.println(\"Finally block is always executed\");\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Finally block is always executed\nException in thread \"main\" java.lang.ArithmeticException: \/ by zero\n        at Main.main(Main.java:4)<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have used the&nbsp;<code>try<\/code>&nbsp;block along with the&nbsp;<code>finally<\/code>&nbsp;block. We can see that the code inside the&nbsp;<code>try<\/code>&nbsp;block is causing an exception.<\/p>\n\n\n\n<p>However, the code inside the&nbsp;<code>finally<\/code>&nbsp;block is executed irrespective of the exception.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"try-catch-finally\">Java try&#8230;catch&#8230;finally block<\/h2>\n\n\n\n<p>In Java, we can also use the finally block after the&nbsp;<code>try...catch<\/code>&nbsp;block. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\n\nclass ListOfNumbers {\n\n  \/\/ create an integer array\n  private int&#91;] list = {5, 6, 8, 9, 2};\n\n  \/\/ method to write data from array to a fila\n  public void writeList() {\n    PrintWriter out = null;\n\n    try {\n      System.out.println(\"Entering try statement\");\n\n      \/\/ creating a new file OutputFile.txt\n      out = new PrintWriter(new FileWriter(\"OutputFile.txt\"));\n\n      \/\/ writing values from list array to Output.txt\n      for (int i = 0; i &lt; 7; i++) {\n        out.println(\"Value at: \" + i + \" = \" + list&#91;i]);\n      }\n    }\n    \n    catch (Exception e) {\n      System.out.println(\"Exception =&gt; \" + e.getMessage());\n    }\n    \n    finally {\n      \/\/ checking if PrintWriter has been opened\n      if (out != null) {\n        System.out.println(\"Closing PrintWriter\");\n        \/\/ close PrintWriter\n        out.close();\n      }\n      \n      else {\n        System.out.println(\"PrintWriter not open\");\n      }\n    }\n\n  }\n}\n\nclass Main {\n  public static void main(String&#91;] args) {\n    ListOfNumbers list = new ListOfNumbers();\n    list.writeList();\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Entering try statement\nException =&gt; Index 5 out of bounds for length 5\nClosing PrintWriter<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created an array named&nbsp;<var>list<\/var>&nbsp;and a file named&nbsp;<var>output.txt<\/var>. Here, we are trying to read data from the array and storing to the file.<\/p>\n\n\n\n<p>Notice the code,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>for (int i = 0; i &lt; 7; i++) {\n  out.println(\"Value at: \" + i + \" = \" + list&#91;i]);\n}<\/code><\/pre>\n\n\n\n<p>Here, the size of the array is&nbsp;<code>5<\/code>&nbsp;and the last element of the array is at&nbsp;<code>list[4]<\/code>. However, we are trying to access elements at&nbsp;<code><em>a[5]<\/em><\/code>&nbsp;and&nbsp;<code>a[6]<\/code>.<\/p>\n\n\n\n<p>Hence, the code generates an exception that is caught by the catch block.<\/p>\n\n\n\n<p>Since the&nbsp;<code>finally<\/code>&nbsp;block is always executed, we have included code to close the&nbsp;<code>PrintWriter<\/code>&nbsp;inside the finally block.<\/p>\n\n\n\n<p>It is a good practice to use finally block to include important cleanup code like closing a file or connection.<\/p>\n\n\n\n<p><strong>Note<\/strong>: There are some cases when a&nbsp;<code>finally<\/code>&nbsp;block does not execute:<\/p>\n\n\n\n<ul><li>Use of&nbsp;<code>System.exit()<\/code>&nbsp;method<\/li><li>An exception occurs in the&nbsp;<code>finally<\/code>&nbsp;block<\/li><li>The death of a thread<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"multiple-catch\">Multiple Catch blocks<\/h2>\n\n\n\n<p>For each&nbsp;<code>try<\/code>&nbsp;block, there can be zero or more&nbsp;<code>catch<\/code>&nbsp;blocks. Multiple&nbsp;<code>catch<\/code>&nbsp;blocks allow us to handle each exception differently.<\/p>\n\n\n\n<p>The argument type of each&nbsp;<code>catch<\/code>&nbsp;block indicates the type of exception that can be handled by it. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ListOfNumbers {\n  public int&#91;] arr = new int&#91;10];\n\n  public void writeList() {\n\n    try {\n      arr&#91;10] = 11;\n    }\n    \n    catch (NumberFormatException e1) {\n      System.out.println(\"NumberFormatException =&gt; \" + e1.getMessage());\n    }\n    \n    catch (IndexOutOfBoundsException e2) {\n      System.out.println(\"IndexOutOfBoundsException =&gt; \" + e2.getMessage());\n    }\n\n  }\n}\n\nclass Main {\n  public static void main(String&#91;] args) {\n    ListOfNumbers list = new ListOfNumbers();\n    list.writeList();\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>IndexOutOfBoundsException =&gt; Index 10 out of bounds for length 10<\/samp><\/code><\/pre>\n\n\n\n<p>In this example, we have created an integer array named&nbsp;<code>arr<\/code>&nbsp;of size&nbsp;<strong>10<\/strong>.<\/p>\n\n\n\n<p>Since the array index starts from&nbsp;<strong>0<\/strong>, the last element of the array is at&nbsp;<code>arr[9]<\/code>. Notice the statement,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>arr&#91;10] = 11;<\/code><\/pre>\n\n\n\n<p>Here, we are trying to assign a value to the index&nbsp;<strong>10<\/strong>. Hence,&nbsp;<code>IndexOutOfBoundException<\/code>&nbsp;occurs.<\/p>\n\n\n\n<p>When an exception occurs in the&nbsp;<code>try<\/code>&nbsp;block,<\/p>\n\n\n\n<ul><li>The exception is thrown to the first&nbsp;<code>catch<\/code>&nbsp;block. The first&nbsp;<code>catch<\/code>&nbsp;block does not handle an&nbsp;<code>IndexOutOfBoundsException<\/code>, so it is passed to the next&nbsp;<code>catch<\/code>&nbsp;block.<\/li><li>The second&nbsp;<code>catch<\/code>&nbsp;block in the above example is the appropriate exception handler because it handles an&nbsp;<code>IndexOutOfBoundsException<\/code>. Hence, it is executed.<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"multiple-exceptions\">Catching Multiple Exceptions<\/h3>\n\n\n\n<p>From Java SE 7 and later, we can now catch more than one type of exception with one&nbsp;<code>catch<\/code>&nbsp;block.<\/p>\n\n\n\n<p>This reduces code duplication and increases code simplicity and efficiency.<\/p>\n\n\n\n<p>Each exception type that can be handled by the&nbsp;<code>catch<\/code>&nbsp;block is separated using a vertical bar&nbsp;<code>|<\/code>.<\/p>\n\n\n\n<p>Its syntax is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n  \/\/ code\n} catch (ExceptionType1 | Exceptiontype2 ex) { \n  \/\/ catch block\n}<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"try-resource\">Java try-with-resources statement<\/h3>\n\n\n\n<p>The&nbsp;<strong>try-with-resources<\/strong>&nbsp;statement is a try statement that has one or more resource declarations.<\/p>\n\n\n\n<p>Its syntax is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try (resource declaration) {\n  \/\/ use of the resource\n} catch (ExceptionType e1) {\n  \/\/ catch block\n}<\/code><\/pre>\n\n\n\n<p>The resource is an object to be closed at the end of the program. It must be declared and initialized in the try statement.<\/p>\n\n\n\n<p>Let&#8217;s take an example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try (PrintWriter out = new PrintWriter(new FileWriter(\"OutputFile.txt\")) {\n  \/\/ use of the resource\n}<\/code><\/pre>\n\n\n\n<p>The&nbsp;<strong>try-with-resources<\/strong>&nbsp;statement is also referred to as&nbsp;<strong>automatic resource management<\/strong>. This statement automatically closes all the resources at the end of the statement.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will learn about the try catch statement in Java with the help of examples. The&nbsp;try&#8230;catch&nbsp;block in Java is used to handle exceptions and prevents the abnormal termination of the program. Here&#8217;s the syntax of a&nbsp;try&#8230;catch&nbsp;block in Java. The&nbsp;try&nbsp;block includes the code that might generate an exception. The&nbsp;catch&nbsp;block includes the code that [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[569],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1245"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1245"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1245\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1245"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1245"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1245"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}