{"id":22265,"date":"2020-01-29T12:24:25","date_gmt":"2020-01-29T12:24:25","guid":{"rendered":"https:\/\/cnsfly.com\/vytcdc\/?p=22265"},"modified":"2024-08-22T09:52:24","modified_gmt":"2024-08-22T09:52:24","slug":"exception-handling-in-java","status":"publish","type":"post","link":"https:\/\/cnsfly.com\/vytcdc\/exception-handling-in-java\/","title":{"rendered":"Exception Handling in Java"},"content":{"rendered":"<p>In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.<\/p>\n<p>The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application cannot be terminated.<\/p>\n<p>An exception can occur for many different reasons. Following are some scenarios where an exception occurs.<\/p>\n<p><strong>Advantage of Exception Handling<\/strong><\/p>\n<p>An exception normally disrupts the normal flow of the application that is why we use exception handling. Let\u2019s take a scenario:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">statement 1;\r\nstatement 2;\r\nstatement 3; \/\/exception occurs\r\nstatement 4;\r\nstatement 5;\r\nstatement 6;\r\nstatement 7;\r\nstatement 8;\r\nstatement 9;\r\nstatement 10;<\/pre>\n<p>Assume that, there are 10 lines in our program, and the exception came at the 3rd line of our program, if we have not handle the exception, then the program abnormally terminated and from the line 4 to line 10 will not be executed.<\/p>\n<p>If we handle the exception, the JVM will take care of exception and the remaining lines will be executed completely.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h3><strong>Hierarchy of Java Exception classes<\/strong><\/h3>\n<p>The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"alignnone wp-image-23755 size-full\" src=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2020\/01\/Exception-in-java1-1.png\" alt=\"\" width=\"675\" height=\"490\" srcset=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2020\/01\/Exception-in-java1-1.png 675w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2020\/01\/Exception-in-java1-1-300x218.png 300w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2020\/01\/Exception-in-java1-1-600x436.png 600w\" sizes=\"(max-width: 675px) 100vw, 675px\" \/><\/p>\n<p>\/\/ Java program to demonstrate how exception is thrown.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">class ThrowsExecp{\r\npublic static void main(String args[]){\r\nString str = null;\r\nSystem.out.println(str.length());\r\n}\r\n}<\/pre>\n<p>Exception in thread \u201cmain\u201d java.lang.NullPointerException<\/p>\n<p>at ThrowsExecp.main(File.java:8)<\/p>\n<p><strong>Types of Java Exceptions<\/strong><br \/>\nChecked Exception<br \/>\nUnchecked Exception<\/p>\n<p><strong>Checked exceptions<\/strong><\/p>\n<p>All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled\/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc.<\/p>\n<p><strong>Unchecked Exceptions<\/strong><\/p>\n<p>Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it\u2019s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.<\/p>\n<p>Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword.<\/p>\n<p><strong>Java try and catch<\/strong><\/p>\n<p>We can handle exception either try catch or throws keyword.<\/p>\n<p>See the example bellow.<\/p>\n<p>This will generate an error, because myNumbers[10] does not exist.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"js\">public class MyClass {\r\npublic static void main(String[ ] args) {\r\nint[] myNumbers = {1, 2, 3};\r\nSystem.out.println(myNumbers[10]); \/\/ error!\r\n}\r\n}<\/pre>\n<p>The output will be something like this:<\/p>\n<p>Exception in thread \u201cmain\u201d java.lang.ArrayIndexOutOfBoundsException: 10<br \/>\nat MyClass.main(MyClass.java:4)<\/p>\n<p>For the above error we need to handle exception like mentioned bellow.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public class MyClass {\r\npublic static void main(String[ ] args) {\r\ntry {\r\nint[] myNumbers = {1, 2, 3};\r\nSystem.out.println(myNumbers[10]);\r\n} catch (Exception e) {\r\nSystem.out.println(\"Something went wrong.\");\r\n}\r\n}\r\n}<\/pre>\n<p>The output will be:<br \/>\nSomething went wrong.<\/p>\n<p><strong>Finally<\/strong><\/p>\n<p>The finally statement lets you execute code, after try\u2026catch, regardless of the result:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public class MyClass {\r\npublic static void main(String[] args) {\r\ntry {\r\nint[] myNumbers = {1, 2, 3};\r\nSystem.out.println(myNumbers[10]);\r\n} catch (Exception e) {\r\nSystem.out.println(\"Something went wrong.\");\r\n} finally {\r\nSystem.out.println(\"The 'try catch' is finished.\");\r\n}\r\n}\r\n}<\/pre>\n<p><strong>The throw keyword<\/strong><\/p>\n<p>The throw statement allows you to create a custom error.<\/p>\n<p>The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:<\/p>\n<p><strong>Example:<\/strong><\/p>\n<p>Throw an exception if age is below 18 (print \u201cAccess denied\u201d). If age is 18 or older, print \u201cAccess granted\u201d:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public class MyClass {\r\nstatic void checkAge(int age) {\r\nif (age &lt; 18) {\r\nthrow new ArithmeticException(\"Access denied - You must be at least 18 years old.\");\r\n}\r\nelse {\r\nSystem.out.println(\"Access granted - You are old enough!\");\r\n}\r\n}\r\npublic static void main(String[] args) {\r\ncheckAge(15); \/\/ Set age to 15 (which is below 18...)\r\n}\r\n}<\/pre>\n<p>The Output will be<\/p>\n<p>Exception in thread \u201cmain\u201d java.lang.ArithmeticException: Access denied \u2013 You must be at least 18 years old.at MyClass.checkAge (MyClass.java:4)at MyClass.main(MyClass.java:12)<\/p>\n<p>The Output will be<\/p>\n<p>If age was 20, you would not get an exception:<\/p>\n<p>checkAge(20);<\/p>\n<p>The Output will be<\/p>\n<p>Access granted \u2013 You are old enough!<\/p>\n<p><strong>Throws<\/strong><\/p>\n<p>Throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.<\/p>\n<p><em>Note : Throws keyword we cannot use in Unchecked Exceptions, we can only use in Checked Exception<\/em><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">class Test\r\n{\r\npublic static void main(String[] args) throws InterruptedException\r\n{\r\nThread.sleep(10000);\r\nSystem.out.println(\"Hello TCDC\");\r\n}\r\n}<\/pre>\n<p>In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello TCDC<\/p>\n<p><strong>Another Example:<\/strong><\/p>\n<p>\/\/ Java program to demonstrate working of throws<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">class ThrowsExecp\r\n{\r\nstatic void fun() throws IllegalAccessException\r\n{\r\nSystem.out.println(\"Inside fun(). \");\r\nthrow new IllegalAccessException(\"demo\");\r\n}\r\npublic static void main(String args[])\r\n{\r\ntry\r\n{\r\nfun();\r\n}\r\ncatch(IllegalAccessException e)\r\n{\r\nSystem.out.println(\"caught in main.\");\r\n}\r\n}\r\n}<\/pre>\n<p>throws keyword is required only for checked exception.<\/p>\n<p>By the help of throws keyword we can provide information to the caller of the method about the exception.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. The Exception Handling in Java is<\/p>\n","protected":false},"author":1,"featured_media":28919,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[76],"tags":[25,26],"class_list":["post-22265","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-design","tag-development"],"_links":{"self":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22265","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/comments?post=22265"}],"version-history":[{"count":1,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22265\/revisions"}],"predecessor-version":[{"id":29451,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22265\/revisions\/29451"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/media\/28919"}],"wp:attachment":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/media?parent=22265"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/categories?post=22265"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/tags?post=22265"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}