{"id":3221,"date":"2020-01-29T15:20:30","date_gmt":"2020-01-29T09:50:30","guid":{"rendered":"https:\/\/cns72.com\/vytcdc.com.sg\/?p=3221"},"modified":"2020-01-30T19:05:25","modified_gmt":"2020-01-30T13:35:25","slug":"exception-handling-in-java","status":"publish","type":"post","link":"https:\/\/cns72.com\/vytcdc.com.sg\/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>A user has entered an invalid data.<br \/>\nA file that needs to be opened cannot be found.<br \/>\nA network connection has been lost in the middle of communications or the JVM has run out of memory.<\/p>\n<p>Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.<\/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&#8217;s take a scenario:<\/p>\n<ul style=\"margin-left: 56px; list-style: none;\">\n<li>statement 1;<\/li>\n<li>statement 2;<\/li>\n<li>statement 3; \/\/exception occurs<\/li>\n<li>statement 4;<\/li>\n<li>statement 5;<\/li>\n<li>statement 6;<\/li>\n<li>statement 7;<\/li>\n<li>statement 8;<\/li>\n<li>statement 9;<\/li>\n<li>statement 10;<\/li>\n<\/ul>\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><strong>Hierarchy of Java Exception classes<\/strong><\/p>\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 loading=\"lazy\" class=\"alignnone size-full wp-image-3228\" src=\"http:\/\/183.82.34.162\/vytcdc\/wp-content\/uploads\/2020\/01\/download.jpg\" alt=\"\" width=\"700\" height=\"350\" \/><\/p>\n<p><img loading=\"lazy\" class=\"alignnone size-full wp-image-3223\" src=\"http:\/\/183.82.34.162\/vytcdc\/wp-content\/uploads\/2020\/01\/Exception-in-java1.png\" alt=\"\" width=\"675\" height=\"490\" \/><\/p>\n<p>\/\/ Java program to demonstrate how exception is thrown.<\/p>\n<p>class ThrowsExecp{<br \/>\npublic static void main(String args[]){<br \/>\nString str = null;<br \/>\nSystem.out.println(str.length());<br \/>\n}<br \/>\n}<\/p>\n<p>Exception in thread &#8220;main&#8221; 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<p>public class MyClass {<br \/>\npublic static void main(String[ ] args) {<br \/>\nint[] myNumbers = {1, 2, 3};<br \/>\nSystem.out.println(myNumbers[10]); \/\/ error!<br \/>\n}<br \/>\n}<\/p>\n<p>The output will be something like this:<\/p>\n<p>Exception in thread &#8220;main&#8221; 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<p>public class MyClass {<br \/>\npublic static void main(String[ ] args) {<br \/>\ntry {<br \/>\nint[] myNumbers = {1, 2, 3};<br \/>\nSystem.out.println(myNumbers[10]);<br \/>\n} catch (Exception e) {<br \/>\nSystem.out.println(&#8220;Something went wrong.&#8221;);<br \/>\n}<br \/>\n}<br \/>\n}<\/p>\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&#8230;catch, regardless of the result:<\/p>\n<p>public class MyClass {<br \/>\npublic static void main(String[] args) {<br \/>\ntry {<br \/>\nint[] myNumbers = {1, 2, 3};<br \/>\nSystem.out.println(myNumbers[10]);<br \/>\n} catch (Exception e) {<br \/>\nSystem.out.println(&#8220;Something went wrong.&#8221;);<br \/>\n} finally {<br \/>\nSystem.out.println(&#8220;The &#8216;try catch&#8217; is finished.&#8221;);<br \/>\n}<br \/>\n}<br \/>\n}<\/p>\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 &#8220;Access denied&#8221;). If age is 18 or older, print &#8220;Access granted&#8221;:<\/p>\n<p>public class MyClass {<br \/>\nstatic void checkAge(int age) {<br \/>\nif (age &lt; 18) {<br \/>\nthrow new ArithmeticException(&#8220;Access denied &#8211; You must be at least 18 years old.&#8221;);<br \/>\n}<br \/>\nelse {<br \/>\nSystem.out.println(&#8220;Access granted &#8211; You are old enough!&#8221;);<br \/>\n}<br \/>\n}<br \/>\npublic static void main(String[] args) {<br \/>\ncheckAge(15); \/\/ Set age to 15 (which is below 18&#8230;)<br \/>\n}<br \/>\n}<\/p>\n<p>The Output will be<\/p>\n<p>Exception in thread &#8220;main&#8221; java.lang.ArithmeticException: Access denied &#8211; 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 &#8211; 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>class tst<br \/>\n{<br \/>\npublic static void main(String[] args) throws InterruptedException<br \/>\n{<br \/>\nThread.sleep(10000);<br \/>\nSystem.out.println(&#8220;Hello TCDC&#8221;);<br \/>\n}<br \/>\n}<\/p>\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<p>class ThrowsExecp<br \/>\n{<br \/>\nstatic void fun() throws IllegalAccessException<br \/>\n{<br \/>\nSystem.out.println(&#8220;Inside fun(). &#8220;);<br \/>\nthrow new IllegalAccessException(&#8220;demo&#8221;);<br \/>\n}<br \/>\npublic static void main(String args[])<br \/>\n{<br \/>\ntry<br \/>\n{<br \/>\nfun();<br \/>\n}<br \/>\ncatch(IllegalAccessException e)<br \/>\n{<br \/>\nSystem.out.println(&#8220;caught in main.&#8221;);<br \/>\n}<br \/>\n}<br \/>\n}<\/p>\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 one of the powerful mechanism to handle the runtime errors so that normal flow of the application cannot be terminated. An exception can occur for [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3224,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[45],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.0.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Exception Handling in Java - TCDC<\/title>\n<link rel=\"canonical\" href=\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Exception Handling in Java - TCDC\" \/>\n<meta property=\"og:description\" content=\"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 one of the powerful mechanism to handle the runtime errors so that normal flow of the application cannot be terminated. An exception can occur for [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"TCDC\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vytcdc\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-01-29T09:50:30+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-01-30T13:35:25+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/cns72.com\/vytcdc.com.sg\/wp-content\/uploads\/2020\/01\/Exception-in-java1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"675\" \/>\n\t<meta property=\"og:image:height\" content=\"490\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vytcdc\" \/>\n<meta name=\"twitter:site\" content=\"@vytcdc\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"4 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/#website\",\"url\":\"https:\/\/cns72.com\/vytcdc.com.sg\/\",\"name\":\"TCDC\",\"description\":\"Career Development Courses\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/cns72.com\/vytcdc.com.sg\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/cns72.com\/vytcdc.com.sg\/wp-content\/uploads\/2020\/01\/Exception-in-java1.png\",\"width\":675,\"height\":490},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/#webpage\",\"url\":\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/\",\"name\":\"Exception Handling in Java - TCDC\",\"isPartOf\":{\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/#primaryimage\"},\"datePublished\":\"2020-01-29T09:50:30+00:00\",\"dateModified\":\"2020-01-30T13:35:25+00:00\",\"author\":{\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/#\/schema\/person\/c57e5f7b91685a93f23a57aaafd38e82\"},\"breadcrumb\":{\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/\",\"url\":\"https:\/\/cns72.com\/vytcdc.com.sg\/\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/\",\"url\":\"https:\/\/cns72.com\/vytcdc.com.sg\/exception-handling-in-java\/\",\"name\":\"Exception Handling in Java\"}}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/#\/schema\/person\/c57e5f7b91685a93f23a57aaafd38e82\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/cns72.com\/vytcdc.com.sg\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/f8f959f70994a4401c8704d6b2143474?s=96&d=mm&r=g\",\"caption\":\"admin\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/posts\/3221"}],"collection":[{"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/comments?post=3221"}],"version-history":[{"count":0,"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/posts\/3221\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/media\/3224"}],"wp:attachment":[{"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/media?parent=3221"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/categories?post=3221"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cns72.com\/vytcdc.com.sg\/wp-json\/wp\/v2\/tags?post=3221"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}