{"id":1243,"date":"2022-02-26T06:40:47","date_gmt":"2022-02-26T06:40:47","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1243"},"modified":"2022-02-26T06:40:47","modified_gmt":"2022-02-26T06:40:47","slug":"java-exception-handling","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/26\/java-exception-handling\/","title":{"rendered":"Java Exception Handling"},"content":{"rendered":"\n<p>In the tutorial, we will learn about different approaches of exception handling in Java with the help of examples.<\/p>\n\n\n\n<p id=\"introduction\">In the last tutorial, we learned about\u00a0Java exceptions. We know that exceptions abnormally terminate the execution of a program.<\/p>\n\n\n\n<p>This is why it is important to handle exceptions. Here&#8217;s a list of different approaches to handle exceptions in Java.<\/p>\n\n\n\n<ul><li>try&#8230;catch block<\/li><li>finally block<\/li><li>throw and throws keyword<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"try-catch\">1. Java try&#8230;catch block<\/h2>\n\n\n\n<p>The&nbsp;<a href=\"https:\/\/www.programiz.com\/java-programming\/try-catch\">try-catch<\/a>&nbsp;block is used to handle exceptions in Java. Here&#8217;s the syntax of&nbsp;<code>try...catch<\/code>&nbsp;block:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n  \/\/ code\n}\ncatch(Exception e) {\n  \/\/ code\n}<\/code><\/pre>\n\n\n\n<p>Here, we have placed the code that might generate an exception inside the&nbsp;<code>try<\/code>&nbsp;block. Every&nbsp;<code>try<\/code>&nbsp;block is followed by a&nbsp;<code>catch<\/code>&nbsp;block.<\/p>\n\n\n\n<p>When an exception occurs, it is caught by the&nbsp;<code>catch<\/code>&nbsp;block. The&nbsp;<code>catch<\/code>&nbsp;block cannot be used without the&nbsp;<code>try<\/code>&nbsp;block.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Exception handling using try&#8230;catch<\/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\n      \/\/ code that generate exception\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 example, we are trying to divide a number by&nbsp;<code>0<\/code>. Here, this code generates an exception.<\/p>\n\n\n\n<p>To handle the exception, we have put the code,&nbsp;<code>5 \/ 0<\/code>&nbsp;inside the&nbsp;<code>try<\/code>&nbsp;block. Now when an exception occurs, the rest of the code inside the&nbsp;<code>try<\/code>&nbsp;block is skipped.<\/p>\n\n\n\n<p>The&nbsp;<code>catch<\/code>&nbsp;block catches the exception and statements inside the catch block is executed.<\/p>\n\n\n\n<p>If none of the statements in the&nbsp;<code>try<\/code>&nbsp;block generates an exception, the&nbsp;<code>catch<\/code>&nbsp;block is skipped.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"finally\">2. Java finally block<\/h2>\n\n\n\n<p>In Java, the&nbsp;<code>finally<\/code>&nbsp;block is always executed no matter whether there is an exception or not.<\/p>\n\n\n\n<p>The&nbsp;<code>finally<\/code>&nbsp;block is optional. And, for each&nbsp;<code>try<\/code>&nbsp;block, there can be only one&nbsp;<code>finally<\/code>&nbsp;block.<\/p>\n\n\n\n<p>The basic syntax of&nbsp;<code>finally<\/code>&nbsp;block is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n  \/\/code\n}\ncatch (ExceptionType1 e1) { \n  \/\/ catch block\n}\nfinally {\n  \/\/ finally block always executes\n}<\/code><\/pre>\n\n\n\n<p>If an exception occurs, the&nbsp;<code>finally<\/code>&nbsp;block is executed after the&nbsp;<code>try...catch<\/code>&nbsp;block. Otherwise, it is executed after the try block. For each&nbsp;<code>try<\/code>&nbsp;block, there can be only one&nbsp;<code>finally<\/code>&nbsp;block.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Java Exception Handling using 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      \/\/ code that generates exception\n      int divideByZero = 5 \/ 0;\n    }\n\n    catch (ArithmeticException e) {\n      System.out.println(\"ArithmeticException =&gt; \" + e.getMessage());\n    }\n    \n    finally {\n      System.out.println(\"This is the finally block\");\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\nThis is the finally block<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we are dividing a number by&nbsp;<strong>0<\/strong>&nbsp;inside the&nbsp;<code>try<\/code>&nbsp;block. Here, this code generates an&nbsp;<code>ArithmeticException<\/code>.<\/p>\n\n\n\n<p>The exception is caught by the&nbsp;<code>catch<\/code>&nbsp;block. And, then the&nbsp;<code>finally<\/code>&nbsp;block is executed.<\/p>\n\n\n\n<p><strong>Note<\/strong>: It is a good practice to use the&nbsp;<code>finally<\/code>&nbsp;block. It is because it can include important cleanup codes like,<\/p>\n\n\n\n<ul><li>code that might be accidentally skipped by return, continue or break<\/li><li>closing a file or connection<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"throw-throws\">3. Java throw and throws keyword<\/h2>\n\n\n\n<p>The Java&nbsp;<code>throw<\/code>&nbsp;keyword is used to explicitly throw a single exception.<\/p>\n\n\n\n<p>When we&nbsp;<code>throw<\/code>&nbsp;an exception, the flow of the program moves from the&nbsp;<code>try<\/code>&nbsp;block to the&nbsp;<code>catch<\/code>&nbsp;block.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Exception handling using Java throw<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Main {\n  public static void divideByZero() {\n\n    \/\/ throw an exception\n    throw new ArithmeticException(\"Trying to divide by 0\");\n  }\n\n  public static void main(String&#91;] args) {\n    divideByZero();\n  }\n}<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>Exception in thread \"main\" java.lang.ArithmeticException: Trying to divide by 0\n        at Main.divideByZero(Main.java:5)\n        at Main.main(Main.java:9)<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we are explicitly throwing the&nbsp;<code>ArithmeticException<\/code>&nbsp;using the&nbsp;<code>throw<\/code>&nbsp;keyword.<\/p>\n\n\n\n<p>Similarly, the&nbsp;<code>throws<\/code>&nbsp;keyword is used to declare the type of exceptions that might occur within the method. It is used in the method declaration.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Java throws keyword<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\n\nclass Main {\n  \/\/ declareing the type of exception\n  public static void findFile() throws IOException {\n\n    \/\/ code that may generate IOException\n    File newFile = new File(\"test.txt\");\n    FileInputStream stream = new FileInputStream(newFile);\n  }\n\n  public static void main(String&#91;] args) {\n    try {\n      findFile();\n    }\n    catch (IOException e) {\n      System.out.println(e);\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>java.io.FileNotFoundException: test.txt (The system cannot find the file specified)<\/samp><\/code><\/pre>\n\n\n\n<p>When we run this program, if the file&nbsp;<strong>test.txt<\/strong>&nbsp;does not exist,&nbsp;<code>FileInputStream<\/code>&nbsp;throws a&nbsp;<code>FileNotFoundException<\/code>&nbsp;which extends the&nbsp;<code>IOException<\/code>&nbsp;class.<\/p>\n\n\n\n<p>The&nbsp;<code>findFile()<\/code>&nbsp;method specifies that an&nbsp;<code>IOException<\/code>&nbsp;can be thrown. The&nbsp;<code>main()<\/code>&nbsp;method calls this method and handles the exception if it is thrown.<\/p>\n\n\n\n<p>If a method does not handle exceptions, the type of exceptions that may occur within it must be specified in the&nbsp;<code>throws<\/code>&nbsp;clause.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the tutorial, we will learn about different approaches of exception handling in Java with the help of examples. In the last tutorial, we learned about\u00a0Java exceptions. We know that exceptions abnormally terminate the execution of a program. This is why it is important to handle exceptions. Here&#8217;s a list of different approaches to handle [&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\/1243"}],"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=1243"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1243\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1243"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1243"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1243"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}