{"id":2850,"date":"2020-04-08T10:22:27","date_gmt":"2020-04-08T04:52:27","guid":{"rendered":"http:\/\/artoftesting.com\/?p=2850"},"modified":"2021-04-20T13:34:07","modified_gmt":"2021-04-20T08:04:07","slug":"exception-handling-in-java","status":"publish","type":"post","link":"https:\/\/artoftesting.com\/exception-handling-in-java","title":{"rendered":"Exception Handling in Java"},"content":{"rendered":"\n<p>In this article, we will be learning about exception handling in Java, what they are, how do they arise, and how to handle them for the smooth flow of the program. Exception handling is one of the most important features of Java and one of the reasons why it is such a powerful language. So, let\u2019s begin with the definition of an Exception.&nbsp;<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_73 counter-flat ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Content<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#What_is_an_Exception_in_Java\" title=\"What is an Exception in Java?\">What is an Exception in Java?<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#Difference_between_Error_and_Exception\" title=\"Difference between Error and Exception\">Difference between Error and Exception<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#What_is_Exception_handling_in_Java\" title=\"What is Exception handling in Java?\">What is Exception handling in Java?<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#Types_of_Exceptions\" title=\"Types of Exceptions\">Types of Exceptions<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#Keywords\" title=\"Keywords\">Keywords<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#The_Try_Block\" title=\"The Try Block\">The Try Block<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#The_Catch_Block\" title=\"The Catch Block\">The Catch Block<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#Finally_block\" title=\"Finally block\">Finally block<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#Throw\" title=\"Throw\">Throw<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#Throws\" title=\"Throws\">Throws<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#User-defined_Exceptions\" title=\"User-defined Exceptions\">User-defined Exceptions<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#Common_Exceptions\" title=\"Common Exceptions\">Common Exceptions<\/a><\/li><li class='ez-toc-page-1'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_an_Exception_in_Java\"><\/span><strong>What is an Exception in Java?<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>An exception is an unwanted or unexpected event that occurs at the time of execution. It disrupts the normal flow of the program which often leads to termination of the program or application. <br><br>Exceptions in Java can occur due to several reasons like trying to access an element of an array with an index greater than the size of the array, trying to access a non-existing file in your program, invalid data input, network problems, etc. Fortunately, Java has a robust system for handling such errors to prevent the termination of the program.<br><br><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Difference_between_Error_and_Exception\"><\/span><strong>Difference between Error and Exception<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>An error is something that cannot and should not be handled by the developer. It usually tends to signal the end of your program. Also, signals that the program cannot recover and causes you to exit the program altogether instead of trying to handle it.<br><br>Exceptions can and should be handled by the developer. Otherwise, they will surely lead to abnormal termination of the program. They are objects of a type &#8216;System.Exception&#8217; class and arise when non-fatal and recoverable errors occur during run-time.<br><br><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_Exception_handling_in_Java\"><\/span><strong>What is Exception handling in Java?<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Whenever an exception occurs in Java, an object known as the Exception object is created and handed off to the Java-Runtime System(Java Virtual Machine). The entire program is searched for an exception handler of the type of exception that has occurred. If it finds none, then the default exception handler prints a message to the user regarding the details of the exception that has occurred. Let us take a simple example of an exception, dividing a number by zero.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nclass Exceptions {\n    public static void main(String args&#x5B;]) {\n        int n = 0;\n        double quotient = 234\/n;\n        System.out.println(&quot;Quotient: &quot; + quotient);\n    }\n}\n<\/pre><\/div>\n\n\n<p><br>Compile and execute the above-mentioned code. You will notice that it is successfully compiled but shows an error after trying to execute. Exceptions occur at runtime, therefore, the code was successfully compiled and the compiler found no error in it. But the JVM caught an exception and displayed a message like this-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; gutter: false; title: ; notranslate\" title=\"\">\nException in thread &quot;main&quot; java.lang.ArithmeticException: \/ by zero\n         at Exceptions.main(Exceptions.java:4)\n<\/pre><\/div>\n\n\n<p><br>This message is quite non-user-friendly and won\u2019t make any sense to a lot of users. Thus, we use exception handling to display a user-friendly and understandable message to the users so that they will be able to figure out what went wrong. Now let us see how we can handle the above exception-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nclass Exceptions {\n    public static void main(String args&#x5B;]) {\n        int n = 0;\n        try {\n            double quotient = 234\/n;\n            System.out.println(&quot;Quotient: &quot; + quotient);\n        }\n        catch(ArithmeticException e) {\n            System.out.println(&quot;Division by zero has occurred&quot;);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p><br>I have added the try and catch blocks and handled the exception here. We will study in detail about these blocks in the coming section of the article. For now, you can just copy-paste the code and compile &amp; run it. You will now see a user-friendly and understandable message that you have written for the exception &#8211; &#8220;Division by zero has occurred&#8221;.<br><br>In this way, we have successfully handled the exception. If we don&#8217;t handle the exception properly, an unfriendly message containing the details of the exception object will appear and the program will terminate abruptly and abnormally. But if we handle the exception properly then the rest of the program will execute with a friendly\/meaningful message. This is the main advantage of Exception Handling.<br><br><br><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Types_of_Exceptions\"><\/span><strong>Types of Exceptions<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Java, we have two types of exceptions-<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Checked Exceptions:<\/strong> These are the exceptions that arise during compilation time. The compiler checks for these exceptions and whether the programmer has handled them. If we don&#8217;t handle checked exceptions then, it causes a compilation error and the program will not compile. Examples of checked exceptions are classNotFoundException, SQLException, IOException, etc.&nbsp;<br><br><\/li><li><strong>Unchecked Exceptions: <\/strong>These are the exceptions that arise during run-time. The program will compile but not execute. The developer has to handle these exceptions. Examples of unchecked exceptions: ArrayOutOfBoundException, ArithmeticException, NullPointerException, etc.<br><br><br><\/li><\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Keywords\"><\/span><strong>Keywords<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Now let us study the keywords used in Exception Handling in detail.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Try_Block\"><\/span><br><strong>The Try Block<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The first essential step to exception handling is to enclose the lines which can cause an exception, within the try block. The try block contains those lines which can cause an exception and can have one or more legal lines of code. If an exception occurs at a particular statement of the try block, the rest of the statements will not be executed. Thus, it is recommended to exclude those lines which won\u2019t throw an exception. The try block syntax is-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\ntry {\n  Block of code;\n }\n catch and finally blocks\u2026\n<\/pre><\/div>\n\n\n<p><br>A try block must always be followed by a catch block or finally block or both.<br><br><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Catch_Block\"><\/span>The Catch Block<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The catch block is required to handle the exception. It contains lines of code that will be executed if an exception occurs. Each catch block is an exception handler that handles the type of exception specified by the argument. The argument type<em> ExceptionType<\/em> declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. <br><br>The Throwable class is the super-class of all the errors and exceptions in Java. In the previous example, the class ArithmeticException is an instance of a Throwable class and is thrown by the JVM to handle the arithmetic exceptions. To declare the exception type that the catch block will handle, we need to know the type of Exception that can be thrown by the JVM in the try block. The syntax of the catch block is-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\ntry {\ncode;\n}\ncatch(ExceptionType e1) {\ncode;\n} \ncatch(ExceptionType e2) {\n code;\n}\n<\/pre><\/div>\n\n\n<p><br>The try block has to be followed by a catch block. No lines of code can come in between. There may be multiple catch blocks to one try block. Each catch block handles different types of exceptions. The catch block is executed as and when the exception matching the exception type in the handler is invoked.<\/p>\n\n\n\n<p>&nbsp;A few points to be remembered for the try-catch block are:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>A single try block can have multiple catch blocks and the try block contains only those statements which can cause an exception.<br><\/li><li>A generic catch block that does not have any specific exception handling type can handle all types of exceptions.<br><\/li><li>Corresponding catch blocks are executed for that specific type of exception. Example- catch(ArithmeticException e) will handle only arithmetic exceptions, catch(NullPointException e) will handle only NullPointExceptions.&nbsp;<br><\/li><li>If no exception occurs, then all the catch blocks will be completely ignored.<br><br><\/li><\/ol>\n\n\n\n<p>An example to demonstrate the use of multiple catch blocks is-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nclass Exceptions {\n    public static void main(String args&#x5B;]) {\n        int n = 0;\n        int A&#x5B;] = {1,2,3,4,5};\n        try {\n            System.out.println(&quot;Element: &quot; + A&#x5B;7]);\n            double quotient = 234\/n;\n            System.out.println(&quot;Quotient: &quot; + quotient);\n        }\n        catch(ArithmeticException e) {\n            System.out.println(&quot;Division by zero has occurred&quot;);\n        }\n        catch(ArrayIndexOutOfBoundsException e) {\n            System.out.println(&quot;Out of bound index has occurred&quot;);\n        }\n        catch(Exception e) {\n            System.out.println(&quot;Some other exception has occurred&quot;);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<div style=\"height:25px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Finally_block\"><\/span><br><strong>Finally block<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The lines contained inside the &#8216;finally&#8217; block will be executed whether or not an exception occurs. This block is written after the end of all the catch blocks. This block is not just useful in handling exceptions but also helps the programmer to avoid cleaning up the code that may have been bypassed by a continue, return or break statement. For example, we can have statements in &#8216;finally&#8217; that close the database connection. So that even if there is an exception, we are sure that the database connection will get closed. Finally syntax-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nfinally {\n   System.out.println(&quot;Exited from the try-catch block&quot;);\n}\n<\/pre><\/div>\n\n\n<div style=\"height:25px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Throw\"><\/span><strong>Throw<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>For a catch block to handle an exception, it must be thrown by someone or something. Either the programmer throws it or the JVM does it. But in either case, the keyword throw is used. We have seen that an instance of the Throwable class has been thrown whenever an exception arises. <br><br>By using the throw keyword, we can create our own set of conditions to throw an exception explicitly. We use this keyword to throw custom exceptions. The syntax and an example of the throw keyword is-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nthrow instanceOfThrowableClass; \/\/ syntax\nthrow new NullPointerException(&quot;Null pointer Exception&quot;); \/\/example\n\n<\/pre><\/div>\n\n\n<p><br>Remember that we can throw only those classes which are instances of the Throwable class like ArithmeticException, ArrayIndexOutOfBoundException, etc. We can also create our own exception classes and throw them but we will learn about that later in this article. For now, remember that we can throw only those objects which have been inherited from the Throwable class. <br><br>An example to find out whether a student is eligible to sit for an exam based on his\/her age. If he\/she is older than 15 years, he\/she will be eligible for the exam otherwise not. Here, we can explicitly throw an exception with a suitable message with a condition based on age. Here\u2019s the code.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\npublic class ThrowExample {\n   static void checkEligibilty(int age){ \n    System.out.println(&quot;Age: &quot; + age);\n    try{\n      if(age&amp;lt;15) {\n         throw new ArithmeticException(&quot;The Student is not eligible for examination&quot;); \n      }\n      else {\n         System.out.println(&quot;The Student is Eligible!&quot;); \n      }\n    }\n    catch(ArithmeticException e) {\n      System.out.println(e.getMessage());\n    }\n   } \n\n   public static void main(String args&#x5B;]){ \n     System.out.println(&quot;Let's find out your eligibility!&quot;);\n     checkEligibilty(12); \n     System.out.println(&quot;Thank you&quot;); \n } \n}\n<\/pre><\/div>\n\n\n<p><br>The output will be-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; gutter: false; title: ; notranslate\" title=\"\">\nLet's find out your eligibility!\nAge: 12\nThe Student is not eligible for examination\nThank you\n<\/pre><\/div>\n\n\n<p><br>In the above code, we have explicitly thrown an ArithmeticException with a message under a condition. We have enclosed it in a try-catch block and display the message of the exception using the in-built method getMessage(). In this way, we can define custom errors using the throw keyword.<br><br><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Throws\"><\/span><strong>Throws<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The throws keyword is used to indicate that a particular method may throw an exception of a specific type. The caller of this method has to handle the exception using a try-catch block. The throws keyword declares an exception and if not handled, could cause compilation errors. This keyword is used to handle only &#8216;checked exceptions&#8217;, i.e., compile-time exceptions. Examples of using throws keyword are-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nimport java.io.*;\nclass ThrowsExample {\n    public static void main(String args&#x5B;]) throws IOException {\n        throw new IOException(&quot;Exception has arised.&quot;);\n    }\n}\n<\/pre><\/div>\n\n\n<p><br>In the above example, we used the throws keyword in the signature of the main() thus, JVM directly handled the exception we explicitly invoked. Another example-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nimport java.io.*;\nclass Example {\n    public void artOfTesting(int n) throws IOException, ClassNotFoundException{\n        System.out.println(&quot;Inside artOfTesting&quot;);\n        if(n&lt;0)\n            throw new IOException(&quot;IOException occurred&quot;);\n        else\n            throw new ClassNotFoundException(&quot;ClassNotFoundException occurred&quot;);\n    }\n}\n\n\nclass ThrowsExample {\n    public static void main(String args&#x5B;]) {\n        Example E = new Example();\n        try {\n            E.artOfTesting(-1);\n        }\n        catch(IOException e) {\n            System.out.println(e.getMessage());\n        }\n        catch(ClassNotFoundException e) {\n            System.out.println(e.getMessage());\n        }\n        finally {\n            System.out.println(&quot;Inside main method&quot;);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p><br>In the above example, I have used two Exceptions with the method artOfTesting() which is allowed in Java with the use of commas.&nbsp;<br><br><br><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"User-defined_Exceptions\"><\/span><strong>User-defined Exceptions<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>As mentioned earlier, we can create our own exception classes. Now we will learn how. These are known as &#8216;user-defined&#8217; or custom exceptions which we create and throw on a particular condition. A &#8216;user-defined&#8217; exception class is created by extending it from the Exception class in Java. Example-<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nclass MyException extends Exception {\n    public MyException(String s){\n        super(s);\n    }\n}\nclass CustomExceptions {\n    public static void main(String args&#x5B;]) throws MyException{\n        try {\n            throw new MyException(&quot;Custom Exception has occurred&quot;);\n        }\n        catch(MyException e) {\n            System.out.println(e.getMessage());\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p><br>Calling the super() here is not mandatory but a good practice. The constructor takes a String as an argument. But this is also not mandatory and we can leave it null. The above code will produce the following output &#8211; &#8220;Custom Exception has occurred&#8221;.<br><br><br><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Common_Exceptions\"><\/span><strong>Common Exceptions<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>A few common exceptions that frequently arise while programming in Java are-<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>ArithmeticException<\/strong>: This exception occurs in case of any unfavorable arithmetic condition e.g. when we divide an integer with zero.<br><br><\/li><li><strong>ArrayIndexOutOfBoundsException<\/strong>: This exception occurs when we try to access a non-existent index of an array.&nbsp;<br><br><\/li><li><strong>NumberFormatException<\/strong>: This exception occurs when we try to convert a string to any numeric value, but the string format is illegal and cannot be converted.<br><br><\/li><li><strong>StringIndexOutOfBoundsException<\/strong>: Similar to the ArrayIndexOutOfBounds exception, this exception arises when a non-existent string index is accessed.<br><br><\/li><li><strong>NullPointerException<\/strong>: This exception occurs when we an object with the value \u201cnull\u201d.<br><br><\/li><li><strong>ClassCastException<\/strong>: This exception occurs when we try to improperly convert a class from one type to another.<br><br><\/li><li><strong>IllegalArgumentException<\/strong>: This exception occurs when we pass an illegal or inappropriate argument to a method.<br><br><\/li><li><strong>IOException<\/strong>: This exception occurs when there has been a failure in the input\/output operations.<br><br><\/li><li><strong>ClassNotFoundException<\/strong>: This exception occurs when the specified class cannot be found in the classpath.<br><br><\/li><li><strong>FileNotFoundException<\/strong>: This exception occurs when an attempt to open a file denoted by a specified pathname has failed.<br><br><\/li><li><strong>EmptyStackException<\/strong>: This exception arises when the pop\/peek operation is performed on an empty stack.<br><br><\/li><\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><strong>Conclusion<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>We have reached the end of our article on Exception handling in Java. By now, we know what exceptions are in Java? How are they different from errors? How to handle exceptions? The different types of exceptions. Keywords used in exception handling. How to throw and catch exceptions? And, how to create custom\/user-defined exceptions?<br><br>Exception Handling is an important part of Java programming since every developer needs to handle exceptions to prevent the application from crashing. So, it is very essential to know how to create, throw, and handle exceptions in Java. Hope you understood all the concepts properly and will be able to apply them. Continue learning!<br><br><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>Don&#8217;t miss out<br><a href=\"http:\/\/artoftesting.com\/java-for-testers\"><strong>Core Java Tutorial Series<\/strong><\/a><\/p><\/blockquote>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will be learning about exception handling in Java, what they are, how do they arise, and how to handle them for the smooth flow of the program. Exception handling is one of the most important features of Java and one of the reasons why it is such a powerful language. So, &#8230; <a title=\"Exception Handling in Java\" class=\"read-more\" href=\"https:\/\/artoftesting.com\/exception-handling-in-java\" aria-label=\"Read more about Exception Handling in Java\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":2855,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8,20],"tags":[],"class_list":["post-2850","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-automation-testing","category-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.0 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Learn Exception Handling in Java [With Examples]<\/title>\n<meta name=\"description\" content=\"Exception handling in Java is one of the most important concepts in Java programming since every developer needs to handle exceptions to prevent the application from crashing.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/artoftesting.com\/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=\"Learn Exception Handling in Java [With Examples]\" \/>\n<meta property=\"og:description\" content=\"Exception handling in Java is one of the most important concepts in Java programming since every developer needs to handle exceptions to prevent the application from crashing.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/artoftesting.com\/exception-handling-in-java\" \/>\n<meta property=\"og:site_name\" content=\"ArtOfTesting\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/facebook.com\/artoftesting\" \/>\n<meta property=\"article:published_time\" content=\"2020-04-08T04:52:27+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-04-20T08:04:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"728\" \/>\n\t<meta property=\"og:image:height\" content=\"416\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Kuldeep Rana\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@theartoftesting\" \/>\n<meta name=\"twitter:site\" content=\"@theartoftesting\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kuldeep Rana\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java#article\",\"isPartOf\":{\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java\"},\"author\":{\"name\":\"Kuldeep Rana\",\"@id\":\"https:\/\/artoftesting.com\/#\/schema\/person\/7846d06225b52c778d160becf65996a5\"},\"headline\":\"Exception Handling in Java\",\"datePublished\":\"2020-04-08T04:52:27+00:00\",\"dateModified\":\"2021-04-20T08:04:07+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java\"},\"wordCount\":1969,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/artoftesting.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java#primaryimage\"},\"thumbnailUrl\":\"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg\",\"articleSection\":[\"Automation Testing\",\"Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/artoftesting.com\/exception-handling-in-java#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java\",\"url\":\"https:\/\/artoftesting.com\/exception-handling-in-java\",\"name\":\"Learn Exception Handling in Java [With Examples]\",\"isPartOf\":{\"@id\":\"https:\/\/artoftesting.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java#primaryimage\"},\"image\":{\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java#primaryimage\"},\"thumbnailUrl\":\"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg\",\"datePublished\":\"2020-04-08T04:52:27+00:00\",\"dateModified\":\"2021-04-20T08:04:07+00:00\",\"description\":\"Exception handling in Java is one of the most important concepts in Java programming since every developer needs to handle exceptions to prevent the application from crashing.\",\"breadcrumb\":{\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/artoftesting.com\/exception-handling-in-java\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java#primaryimage\",\"url\":\"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg\",\"contentUrl\":\"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg\",\"width\":728,\"height\":416,\"caption\":\"Exception handling in Java\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/artoftesting.com\/exception-handling-in-java#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/artoftesting.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Automation Testing\",\"item\":\"https:\/\/artoftesting.com\/category\/automation-testing\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Exception Handling in Java\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/artoftesting.com\/#website\",\"url\":\"https:\/\/artoftesting.com\/\",\"name\":\"ArtOfTesting\",\"description\":\"A Beginners Guide to Testing\",\"publisher\":{\"@id\":\"https:\/\/artoftesting.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/artoftesting.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/artoftesting.com\/#organization\",\"name\":\"ArtOfTesting\",\"url\":\"https:\/\/artoftesting.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/artoftesting.com\/#\/schema\/logo\/image\/\",\"url\":\"http:\/\/artoftesting.com\/wp-content\/uploads\/2019\/12\/Artoftesting_logo.png\",\"contentUrl\":\"http:\/\/artoftesting.com\/wp-content\/uploads\/2019\/12\/Artoftesting_logo.png\",\"width\":400,\"height\":60,\"caption\":\"ArtOfTesting\"},\"image\":{\"@id\":\"https:\/\/artoftesting.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/facebook.com\/artoftesting\",\"https:\/\/x.com\/theartoftesting\",\"https:\/\/www.linkedin.com\/groups\/4797819\/\",\"https:\/\/in.pinterest.com\/artoftesting\/\",\"https:\/\/www.youtube.com\/channel\/UCQ9PUVenvvyrUdDQ9yKn31Q\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/artoftesting.com\/#\/schema\/person\/7846d06225b52c778d160becf65996a5\",\"name\":\"Kuldeep Rana\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/artoftesting.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/cb5979a4b81ca7739c75080e473fad391a8665364e72abaddec9002dd4553326?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/cb5979a4b81ca7739c75080e473fad391a8665364e72abaddec9002dd4553326?s=96&d=mm&r=g\",\"caption\":\"Kuldeep Rana\"},\"description\":\"Kuldeep is the founder and lead author of ArtOfTesting. He is skilled in test automation, performance testing, big data, and CI-CD. He brings his decade of experience to his current role where he is dedicated to educating the QA professionals.\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Learn Exception Handling in Java [With Examples]","description":"Exception handling in Java is one of the most important concepts in Java programming since every developer needs to handle exceptions to prevent the application from crashing.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/artoftesting.com\/exception-handling-in-java","og_locale":"en_US","og_type":"article","og_title":"Learn Exception Handling in Java [With Examples]","og_description":"Exception handling in Java is one of the most important concepts in Java programming since every developer needs to handle exceptions to prevent the application from crashing.","og_url":"https:\/\/artoftesting.com\/exception-handling-in-java","og_site_name":"ArtOfTesting","article_publisher":"https:\/\/facebook.com\/artoftesting","article_published_time":"2020-04-08T04:52:27+00:00","article_modified_time":"2021-04-20T08:04:07+00:00","og_image":[{"width":728,"height":416,"url":"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg","type":"image\/jpeg"}],"author":"Kuldeep Rana","twitter_card":"summary_large_image","twitter_creator":"@theartoftesting","twitter_site":"@theartoftesting","twitter_misc":{"Written by":"Kuldeep Rana","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/artoftesting.com\/exception-handling-in-java#article","isPartOf":{"@id":"https:\/\/artoftesting.com\/exception-handling-in-java"},"author":{"name":"Kuldeep Rana","@id":"https:\/\/artoftesting.com\/#\/schema\/person\/7846d06225b52c778d160becf65996a5"},"headline":"Exception Handling in Java","datePublished":"2020-04-08T04:52:27+00:00","dateModified":"2021-04-20T08:04:07+00:00","mainEntityOfPage":{"@id":"https:\/\/artoftesting.com\/exception-handling-in-java"},"wordCount":1969,"commentCount":0,"publisher":{"@id":"https:\/\/artoftesting.com\/#organization"},"image":{"@id":"https:\/\/artoftesting.com\/exception-handling-in-java#primaryimage"},"thumbnailUrl":"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg","articleSection":["Automation Testing","Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/artoftesting.com\/exception-handling-in-java#respond"]}]},{"@type":"WebPage","@id":"https:\/\/artoftesting.com\/exception-handling-in-java","url":"https:\/\/artoftesting.com\/exception-handling-in-java","name":"Learn Exception Handling in Java [With Examples]","isPartOf":{"@id":"https:\/\/artoftesting.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/artoftesting.com\/exception-handling-in-java#primaryimage"},"image":{"@id":"https:\/\/artoftesting.com\/exception-handling-in-java#primaryimage"},"thumbnailUrl":"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg","datePublished":"2020-04-08T04:52:27+00:00","dateModified":"2021-04-20T08:04:07+00:00","description":"Exception handling in Java is one of the most important concepts in Java programming since every developer needs to handle exceptions to prevent the application from crashing.","breadcrumb":{"@id":"https:\/\/artoftesting.com\/exception-handling-in-java#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/artoftesting.com\/exception-handling-in-java"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/artoftesting.com\/exception-handling-in-java#primaryimage","url":"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg","contentUrl":"https:\/\/artoftesting.com\/wp-content\/uploads\/2020\/04\/exception-handling.jpg","width":728,"height":416,"caption":"Exception handling in Java"},{"@type":"BreadcrumbList","@id":"https:\/\/artoftesting.com\/exception-handling-in-java#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/artoftesting.com\/"},{"@type":"ListItem","position":2,"name":"Automation Testing","item":"https:\/\/artoftesting.com\/category\/automation-testing"},{"@type":"ListItem","position":3,"name":"Exception Handling in Java"}]},{"@type":"WebSite","@id":"https:\/\/artoftesting.com\/#website","url":"https:\/\/artoftesting.com\/","name":"ArtOfTesting","description":"A Beginners Guide to Testing","publisher":{"@id":"https:\/\/artoftesting.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/artoftesting.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/artoftesting.com\/#organization","name":"ArtOfTesting","url":"https:\/\/artoftesting.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/artoftesting.com\/#\/schema\/logo\/image\/","url":"http:\/\/artoftesting.com\/wp-content\/uploads\/2019\/12\/Artoftesting_logo.png","contentUrl":"http:\/\/artoftesting.com\/wp-content\/uploads\/2019\/12\/Artoftesting_logo.png","width":400,"height":60,"caption":"ArtOfTesting"},"image":{"@id":"https:\/\/artoftesting.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/facebook.com\/artoftesting","https:\/\/x.com\/theartoftesting","https:\/\/www.linkedin.com\/groups\/4797819\/","https:\/\/in.pinterest.com\/artoftesting\/","https:\/\/www.youtube.com\/channel\/UCQ9PUVenvvyrUdDQ9yKn31Q"]},{"@type":"Person","@id":"https:\/\/artoftesting.com\/#\/schema\/person\/7846d06225b52c778d160becf65996a5","name":"Kuldeep Rana","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/artoftesting.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/cb5979a4b81ca7739c75080e473fad391a8665364e72abaddec9002dd4553326?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/cb5979a4b81ca7739c75080e473fad391a8665364e72abaddec9002dd4553326?s=96&d=mm&r=g","caption":"Kuldeep Rana"},"description":"Kuldeep is the founder and lead author of ArtOfTesting. He is skilled in test automation, performance testing, big data, and CI-CD. He brings his decade of experience to his current role where he is dedicated to educating the QA professionals."}]}},"_links":{"self":[{"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/posts\/2850","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/comments?post=2850"}],"version-history":[{"count":2,"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/posts\/2850\/revisions"}],"predecessor-version":[{"id":4880,"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/posts\/2850\/revisions\/4880"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/media\/2855"}],"wp:attachment":[{"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/media?parent=2850"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/categories?post=2850"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/artoftesting.com\/wp-json\/wp\/v2\/tags?post=2850"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}