{"id":75,"date":"2020-12-31T22:06:30","date_gmt":"2020-12-31T22:06:30","guid":{"rendered":"https:\/\/bhiggs.x10hosting.com\/practical-java-programming\/?page_id=75"},"modified":"2021-01-16T20:08:02","modified_gmt":"2021-01-16T20:08:02","slug":"exceptions","status":"publish","type":"page","link":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/","title":{"rendered":"Exceptions"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_83 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a06ed3d2add7\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a06ed3d2add7\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Whats_an_Exception\" >What's an Exception?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Why_Should_I_Care\" >Why Should I Care?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Method_Signatures_Exceptions\" >Method Signatures &amp; Exceptions<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Method_Signatures\" >Method Signatures<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Javas_Catch_or_Specify_Requirement\" >Java's Catch or Specify Requirement<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Classification_of_Exceptions\" >Classification of Exceptions<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#The_Throwable_Class_Hierarchy\" >The&nbsp;Throwable&nbsp;Class Hierarchy<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#The_Throwable_Class\" >The&nbsp;Throwable&nbsp;Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Errors\" >Errors<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Exceptions\" >Exceptions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#RuntimeExceptions\" >RuntimeExceptions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Checked_Exceptions\" >Checked Exceptions<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Catching_Exceptions\" >Catching Exceptions<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#The_try_Block\" >The&nbsp;try&nbsp;Block<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#The_catch_Blocks\" >The&nbsp;catch&nbsp;Block(s)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Using_a_Single_Handler_to_Catch_Multiple_Exception_Types\" >Using a Single Handler to Catch Multiple Exception Types<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#A_%22catch-all%22_Block\" >A \"catch-all\" Block<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#The_finally_Block\" >The&nbsp;finally&nbsp;Block<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Throwing_an_Exception\" >Throwing an Exception<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#What_Should_I_Throw\" >What Should I Throw?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Writing_Your_Own_Exception_Class\" >Writing Your Own Exception Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#How_Should_I_Throw_It\" >How Should I Throw It?<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-23\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/exceptions\/#Advice\" >Advice<\/a><\/li><\/ul><\/nav><\/div>\n\n<p>We&#8217;ve actually used exceptions in a few earlier examples, but have delayed talking about them until now. So, let&#8217;s talk about exceptions&#8230;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What&#8217;s an Exception? <\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Exceptions are &#8220;exceptional events&#8221; (not necessarily errors!)<\/li><li>Events that are outside the normal flow of a program<\/li><li>An exception is a subclass of class&nbsp;<strong>Exception<\/strong>&nbsp;(actually,&nbsp;<strong>Throwable<\/strong>, but more on that later)<\/li><li>An exception may be &#8220;thrown&#8221; automatically, or by user code<\/li><li>Can be &#8220;caught&#8221; by user code<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Why_Should_I_Care\"><\/span>Why Should I Care?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Do you check for errors when you make function calls?<ul><li>If not, you should!<\/li><li>If you do, you probably have found that the amount of code that you have to write for error checking is often more than the main flow of the code.<\/li><\/ul><\/li><li>Exceptions allow you to write the main flow of the code more simply, and separate out the nitty-gritty details of what to do when something goes wrong.<\/li><li>Exceptions also allow you to choose where to place the code to handle particular exceptions:<ul><li>Exceptions that must be handled in the current procedure can be<\/li><li>However, some exceptions should be handled by procedures higher up the call stack.<\/li><\/ul><\/li><li>Exceptions allow you to clean up your code to a considerable degree<\/li><li>Exceptions also force you to think about the exceptions that can occur, and have to deal with them.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Method_Signatures_Exceptions\"><\/span>Method Signatures &amp; Exceptions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The first time you see mention of Java exceptions is likely to be when you are calling a method supplied in the Java class library.<\/p>\n\n\n\n<p>For example, let&#8217;s say you want to do something relatively simple, like read a file. Here&#8217;s some code that is intended to do that:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\nimport java.io.FileReader;\n\npublic class Test\n{\n    public static void main(String&#x5B;] args)\n    {\n        \/\/ Open a file for reading\n        FileReader fileReader = new FileReader(&quot;myfile.txt&quot;);\n        \n        \/\/ ...\n    }\n}\n<\/pre><\/div>\n\n\n<p>However, when you compile your program, you find that it gives you the following compilation error:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Exception java.io.FileNotFoundException must be caught, \nor it must be declared in the throws clause of this method.\n        FileReader fileReader = new FileReader(\"myfile.txt\");\n                                ^<\/strong><\/pre>\n\n\n\n<p>What this is telling you is that you can&#8217;t ignore the fact that the <strong>FileReader<\/strong> class constructor may, under some circumstances, throw a <strong>FileNotFoundException<\/strong>. Unless you do something, you can&#8217;t even compile the program.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Method_Signatures\"><\/span>Method Signatures<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>A class method (or constructor) may specify in its signature that it throws an exception. In the case of the&nbsp;<strong>FileReader<\/strong>&nbsp;class constructor, the signature looks like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public FileReader(String fileName) throws FileNotFoundException<\/strong><\/pre>\n\n\n\n<p>A method can specify that it may throw more than one exception (only one exception may be thrown at a time!):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public void doIt() throws SomeException, SomeOtherException, YetAnotherException<\/strong><\/pre>\n\n\n\n<p>In fact, a method&nbsp;<em>must<\/em>&nbsp;specify that it throws an exception&nbsp;<em>if it throws that exception in its body<\/em>. It&nbsp;<em>must<\/em>&nbsp;also specify that it throws an exception&nbsp;<em>if it calls a method that throws that exception<\/em>, or else it&nbsp;<em>must<\/em>&nbsp;catch that exception (see next section).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Java&#8217;s Catch or Specify Requirement<\/h4>\n\n\n\n<p>When a method calls a method which specifies that it throws an exception, Java requires that the calling method do one of two things:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Catch the exception in an exception handler, or:<\/li><li>Specify that it, in turn, throws that exception.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Classification_of_Exceptions\"><\/span>Classification of Exceptions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Throwable_Class_Hierarchy\"><\/span>The&nbsp;<strong>Throwable<\/strong>&nbsp;Class Hierarchy<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Here&#8217;s what the exception class hierarchy looks like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Object\n    Throwable\n        Error\n            &lt;specific Errors&gt;\n        Exception\n            &lt;specific Exceptions&gt;\n            RuntimeException\n                &lt;specific RuntimeExceptions&gt;\n<\/strong><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Throwable_Class\"><\/span>The&nbsp;<strong>Throwable<\/strong>&nbsp;Class<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>The&nbsp;<strong>Throwable<\/strong>&nbsp;class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or of one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java&nbsp;<strong>throw<\/strong>&nbsp;statement. Similarly, only this class or one of its subclasses can be the argument type in a&nbsp;catch&nbsp;clause.<\/p>\n\n\n\n<p>A&nbsp;<strong>Throwable<\/strong>&nbsp;class instance contains a snapshot of the execution stack of its thread at the time the&nbsp;<strong>Throwable<\/strong>&nbsp;was created. It may also contain a message string that gives more information about the error or exception.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Errors\"><\/span><strong>Error<\/strong>s<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>An&nbsp;<strong>Error<\/strong>&nbsp;is a subclass of&nbsp;<strong>Throwable<\/strong>&nbsp;that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The&nbsp;<strong>ThreadDeath<\/strong>&nbsp;error, though a &#8220;normal&#8221; condition, is also a subclass of&nbsp;<strong>Error<\/strong>&nbsp;because most applications should not try to catch it.<\/p>\n\n\n\n<p>A method is not required to declare in its&nbsp;<strong>throws<\/strong>&nbsp;clause any subclasses of&nbsp;<strong>Error<\/strong>&nbsp;that might be thrown during the execution of the method, but not caught, since these errors are abnormal conditions that should never occur.<\/p>\n\n\n\n<p>For examples of specific errors,&nbsp;see below.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Exceptions\"><\/span><strong>Exceptions<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>The class&nbsp;<strong>Exception<\/strong>&nbsp;and its subclasses are a form of&nbsp;<strong>Throwable<\/strong>&nbsp;that indicates conditions a reasonable application might want to catch.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"RuntimeExceptions\"><\/span><strong>RuntimeExceptions<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p><strong>RuntimeException<\/strong>&nbsp;is a subclass of&nbsp;<strong>Exception<\/strong>&nbsp;which is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.<\/p>\n\n\n\n<p>A method is not required to declare in its&nbsp;<strong>throws<\/strong>&nbsp;clause any subclasses of&nbsp;<strong>RuntimeException<\/strong>&nbsp;that might be thrown during the execution of the method, but not caught.<\/p>\n\n\n\n<p>Examples of runtime exceptions are:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Arithmetic exceptions, such as divide-by-zero, etc.<\/li><li>&#8220;Pointer&#8221; exceptions, such as trying to access an object through a null reference,<\/li><li>Indexing exceptions, such as trying to access an array element with an index that is too large or too small.<\/li><li>Etc.<\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Checked_Exceptions\"><\/span>Checked Exceptions<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p><strong><em>Checked Exceptions<\/em><\/strong>&nbsp;are exceptions that:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Are not runtime exceptions and:<\/li><li>Are checked by the compiler.<\/li><\/ol>\n\n\n\n<p>The compiler checks that these exceptions are caught or specified by each method, as appropriate.<\/p>\n\n\n\n<p>Here&#8217;s a taste of what part of the&nbsp;<strong>Throwable<\/strong>&nbsp;class hierarchy looks like in detail:<\/p>\n\n\n\n<p>(Package&nbsp;<strong>java.lang<\/strong>)<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Object\n    Throwable\n        <\/strong><a><strong>Error<\/strong><\/a><strong>\n            LinkageError\n                ClassCircularityError\n                CLassFormatError\n                ExceptionInitializerError\n                IncompatibleClassChangeError\n                    AbstractMethodError\n                    IllegalAccessError\n                    InstantiationError\n                    NoSuchFieldError\n                    NoSuchMethodError\n                NoClassDefFoundError\n                UnsatisfiedLinkError\n                VerifyError\n            ThreadDeath\n            VirtualMachineError\n                InternalError\n                OutOfMemoryError\n                StackOverflowError\n                UnknownError\n        Exception\n            ClassNotFoundException\n            CloneNotSupportedException\n            IllegalAccessException\n            InstantiationException\n            InterruptedException\n            NoSuchFieldException\n            NoSuchMethodException\n            <\/strong><a><strong>RuntimeException<\/strong><\/a><strong>\n                ArithmeticException\n                ArrayStoreException\n                ClassCastException\n                IllegalArgumentException\n                    IllegalThreadStateException\n                    NumberFormatException\n                IllegalMonitorStateException\n                IndexOutOfBoundsException\n                    ArrayIndexOutOfBoundsException\n                    StringIndexOutOfBoundsException\n                NegativeArraySizeException\n                NullPointerException\n                SecurityException<\/strong><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Catching_Exceptions\"><\/span>Catching Exceptions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_try_Block\"><\/span>The&nbsp;<strong>try<\/strong>&nbsp;Block<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>In order to catch exceptions thrown by a set of Java statements, you must first enclose the statements within a&nbsp;<strong>try<\/strong>&nbsp;block:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\n\/\/ (Incomplete...)<\/strong><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_catch_Blocks\"><\/span>The&nbsp;<strong>catch<\/strong>&nbsp;Block(s)<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Following the&nbsp;<code><strong>try<\/strong><\/code>&nbsp;block, you may specify a number of&nbsp;<strong><code>catch<\/code><\/strong>&nbsp;blocks:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\ncatch(<em>ExceptionType<\/em> name)\n{\n    \/\/ Java statements\n}\ncatch(<em>ExceptionType<\/em> name)\n{\n    \/\/ Java statements\n}\n\/\/ more catch blocks ...<\/strong><\/pre>\n\n\n\n<p>Each&nbsp;<code><strong>catch<\/strong><\/code>&nbsp;block is an exception handler which handles the type of exception indicated. Each&nbsp;<em><strong>ExceptionType<\/strong><\/em>&nbsp;must be the name of a class that is a subclass of&nbsp;<strong>Throwable<\/strong>. The name is required, even if you don&#8217;t use it.<\/p>\n\n\n\n<p>The Java runtime system invokes the appropriate exception handler when it is the first handler in the call stack whose <strong>ExceptionType<\/strong> matches the type of the exception being thrown. The system considers it to be a match if the thrown exception can legally be assigned to the handler&#8217;s <strong>ExceptionType<\/strong>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_a_Single_Handler_to_Catch_Multiple_Exception_Types\"><\/span>Using a Single Handler to Catch Multiple Exception Types<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>At times, it might seem necessary to have many exception handlers, each handling a specific exception that your code throws. This can get pretty unwieldy &#8212; especially if you have more&nbsp;<code><strong>catch<\/strong><\/code>&nbsp;blocks than can fit on a page or screen.<\/p>\n\n\n\n<p>To overcome this problem, try to use the exception hierarchy to reduce the number of catch blocks you have to specify. For example, if you&#8217;re trying to catch all exceptions that are subclasses of&nbsp;<strong>IOException<\/strong>, all you have to do is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\ncatch(IOException name)\n{\n    \/\/ Java statements\n}<\/strong><\/pre>\n\n\n\n<p>If you want to catch a&nbsp;<strong>FileNotFoundException<\/strong>&nbsp;(a subclass of&nbsp;<strong>IOException<\/strong>) specifically, as well as catching all other&nbsp;<strong>IOException<\/strong>s, then you can do:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\ncatch(FileNotFoundException e)\n{\n    \/\/ Java statements\n}\ncatch(IOException e)\n{\n    \/\/ Java statements\n}<\/strong><\/pre>\n\n\n\n<p>However, when you do such things, it introduces a&nbsp;<em>catch-block ordering problem<\/em>. For example, the following will&nbsp;<em><strong><u>not<\/u><\/strong><\/em>&nbsp;work:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\ncatch(IOException e)\n{\n    \/\/ Java statements\n}\ncatch(FileNotFoundException e)  \/\/  WRONG!\n{\n    \/\/ Java statements\n}<\/strong><\/pre>\n\n\n\n<p><em><strong>Why not?<\/strong><\/em><\/p>\n\n\n\n<p>The technique of using class inheritance to define &#8220;families&#8221; of related exceptions is very useful:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>To organize exceptions in a logical and consistent way, especially when a family of exceptions relates to a particular piece of functionality.<\/li><li>To reduce the number of exceptions that a method needs to specify.<\/li><li>To reduce the number of exceptions that need to be caught explicitly in a try\/catch block.<\/li><li>To allow you to write code without knowing, a priori, all of the specific exceptions that may be thrown (you can use the superclass exception name as a generic name for all exceptions that extend from it, and later add additional such exceptions.) This is particularly critical when you are writing a framework to be used and extended by others.<\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">A &#8220;catch-all&#8221; Block<\/h4>\n\n\n\n<p>Unlike C++, which has a&nbsp;<code><strong>try<\/strong><\/code>\/<code><strong>catch<\/strong><\/code>&nbsp;block of the form:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ C++ statements\n}\ncatch(<em>SpecificException<\/em> e)\n{\n    \/\/ C++ statements\n}\ncatch(...)\t\/\/ Catch any other exceptions\n{\n    \/\/ C++ statements\n}<\/strong><\/pre>\n\n\n\n<p>Java has no special syntax for a&nbsp;<code><strong>catch<\/strong><\/code>&nbsp;block to catch all (remaining) exceptions. However, you can do the same thing by specifying&nbsp;<strong>Exception<\/strong>&nbsp;(or&nbsp;<strong>Throwable<\/strong>) as the&nbsp;<em><strong>ExceptionType<\/strong><\/em>&nbsp;in the catch block:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\ncatch(<em>ExceptionType<\/em> e)\n{\n    \/\/ Java statements\n}\ncatch(Exception e)\t\/\/ Catch any other exceptions\n{\n    \/\/ Java statements\n}<\/strong><\/pre>\n\n\n\n<p>The following is&nbsp;<em><strong><u>not<\/u><\/strong><\/em>&nbsp;equivalent to the above.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\ncatch(Exception e)\n{\n    \/\/ Java statements\n}\ncatch(<em>ExceptionType<\/em> e)\n{\n    \/\/ Java statements\n}<\/strong>\n<\/pre>\n\n\n\n<p><em><strong>Why not?<\/strong><\/em><\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_finally_Block\"><\/span>The&nbsp;<strong>finally<\/strong>&nbsp;Block<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Optionally, you may specify a&nbsp;<strong>finally<\/strong>&nbsp;block:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\ncatch(<em>ExceptionType1<\/em> name)\n{\n    \/\/ Java statements\n}\ncatch(<em>ExceptionType2<\/em> name)\n{\n    \/\/ Java statements\n}\n\/\/ more catch blocks...\nfinally\n{\n    \/\/ Java statements\n}<\/strong><\/pre>\n\n\n\n<p>or:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Java statements\n}\nfinally\n{\n    \/\/ Java statements\n}<\/strong><\/pre>\n\n\n\n<p>The statements in the&nbsp;<code><strong>finally<\/strong><\/code>&nbsp;block are executed when the <code><strong>try<\/strong><\/code>\/<code><strong>catch<\/strong><\/code> block exits, <em><strong>whether normally or as a result of an exception being thrown<\/strong>.<\/em> This is very useful &#8212; indeed, in some cases indispensable. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Resource res = new Resource();\nres.open();\n\/\/ Do work with res ...\nres.close();<\/strong><\/pre>\n\n\n\n<p>This code looks fine, but doesn&#8217;t work properly when an exception gets thrown during our work with&nbsp;<strong>res<\/strong>. The&nbsp;<code><strong>close()<\/strong><\/code>&nbsp;is never executed, which leaves our resource taking up resources that should have been cleaned up. Perhaps this will result in a failure later on during the program&#8217;s execution.<\/p>\n\n\n\n<p>As one solution to this problem, one could do something like:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Resource res = new Resource();\nres.open();\ntry\n{\n    \/\/ Do work with res ...\n    res.close();\n}\ncatch(Exception e)\n{\n    res.close();\n    throw e;\n}<\/strong><\/pre>\n\n\n\n<p>but this results in duplicated code, especially when you&#8217;re dealing with multiple exceptions. The&nbsp;<strong>finally<\/strong>&nbsp;block solution is much cleaner:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Resource res = new Resource();\nres.open();\ntry\n{\n    \/\/ Do work with res ...\n}\nfinally\n{\n    res.close();\n}<\/strong><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Throwing_an_Exception\"><\/span>Throwing an Exception<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>When you&#8217;re writing a program, you will often be confronted with the task of throwing an exception to indicate that some problem has occurred. Here are some questions you should ask when you encounter this situation:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_Should_I_Throw\"><\/span>What Should I Throw?<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Well, you know that whatever you throw, it has to be a subclass of <strong>Throwable<\/strong>, or the compiler won&#8217;t let you do it. But, aside from that, what choices do you have?<\/p>\n\n\n\n<p>It&#8217;s discouraged to use&nbsp;<strong>Error<\/strong>s, unless you&#8217;re doing something very special, probably with the Java Virtual Machine itself.<\/p>\n\n\n\n<p>Here&#8217;s a list of possibilities:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Use an exception class that&#8217;s already provided:<ul><li>From the java class library (for example,&nbsp;<strong>IllegalArgumentException<\/strong>, or one of many subclasses of&nbsp;<strong>RuntimeException<\/strong>)<\/li><li>From some other class library you&#8217;re using<\/li><\/ul><\/li><li>Use one of your own exception classes<ul><li>A class that already exists<\/li><li>Write a new class<\/li><\/ul><\/li><\/ul>\n\n\n\n<p>You should familiarize yourself with the set of exception classes already available to you, because it&#8217;s possible that one of them would be an appropriate choice for your situation. Look at them first.<\/p>\n\n\n\n<p>Failing that, you have to write your own exception class.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Writing_Your_Own_Exception_Class\"><\/span>Writing Your Own Exception Class<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Once you&#8217;ve made the decision to write your own exception class, you will have to decide what to use as a superclass.<\/p>\n\n\n\n<p>First, see whether there is another exception class that it would be appropriate to extend. If there is, then use that as the superclass.<\/p>\n\n\n\n<p>Another issue is whether you wish to have this exception be a standalone exception, or whether it should be one of a family (hierarchy) of related exceptions. Often, this kind of a family is very useful, and it can avoid lots of cases where methods have long lists of&nbsp;<strong>throws<\/strong>&nbsp;exceptions, and lots of lengthy&nbsp;<strong>catch<\/strong>&nbsp;blocks. If you decide to make a family of exceptions, or add to an existing family, then you will have to come up with the appropriate exception class to use as a superclass.<\/p>\n\n\n\n<p>If you decide not to include the exception into an exception family, then you can use the&nbsp;<code><strong>Exception<\/strong><\/code>&nbsp;class as the superclass:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public class MyVeryOwnException extends Exception { ... }<\/strong><\/pre>\n\n\n\n<p>(filling in the details represented by the above&nbsp;&#8230;&nbsp;).<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><strong><em>Note: <\/em><\/strong>It&#8217;s standard practice to append the string &#8220;<strong>Exception<\/strong>&#8221; to the name of every class that is a subclass (directly or indirectly) of <strong>Exception<\/strong>.<br>Similarly, if you are writing a subclass of the&nbsp;<strong>Error<\/strong> class, it should end its name with the string &#8220;<strong>Error<\/strong>&#8220;.<\/p><\/blockquote>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_Should_I_Throw_It\"><\/span>How Should I Throw It?<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>This is easy: Use the&nbsp;<strong>throw<\/strong>&nbsp;statement:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>throw &lt;exception&gt;<\/strong><\/pre>\n\n\n\n<p>Usually, the exception&#8217;s constructor is used, something like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>throw new EmptyStackException();<\/strong><\/pre>\n\n\n\n<p>or, if you wish to supply more information with the exception:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>throw new EmptyStackException(\"This is an explanation\");<\/strong><\/pre>\n\n\n\n<p>However, if you have an instance of the appropriate exception class already in existence, you can throw it directly.<\/p>\n\n\n\n<p>One case where this is common practice is where you wish to &#8220;re-throw&#8221; an exception that you just caught in an exception handler:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>try\n{\n    \/\/ Try to do something...\n}\ncatch (MyVeryOwnException e)\n{\n    \/\/ Do some cleanup...\n    <\/strong><strong>throw e;<\/strong><strong>\n}<\/strong><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Advice\"><\/span>Advice<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The textbook provides some very useful and relevant advice (&#8220;tips&#8221;) on the use of exceptions (Seventh Edition, pp 576-9):<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Exception Handling is not supposed to replace a simple test<\/li><li>Do not micromanage exceptions<\/li><li>Make good use of the exception hierarchy<\/li><li>Do not squelch exceptions<\/li><li>When you detect an error, &#8220;tough love&#8221; works better than indulgence<\/li><li>Propagating exceptions is not a sign of shame<\/li><\/ol>\n\n\n\n<p>All of these &#8220;tips&#8221; bear close study, and are recommended for everyday exception usage.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We&#8217;ve actually used exceptions in a few earlier examples, but have delayed talking about them until now. So, let&#8217;s talk about exceptions&#8230; What&#8217;s an Exception? Exceptions are &#8220;exceptional events&#8221; (not necessarily errors!)Events that are outside the normal flow of a programAn exception is a subclass of class&nbsp;Exception&nbsp;(actually,&nbsp;Throwable, but more on that later)An exception may be [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":34,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_eb_attr":"","_uag_custom_page_level_css":"","ocean_post_layout":"left-sidebar","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"ocs-course-topics-sidebar","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","footnotes":""},"class_list":["post-75","page","type-page","status-publish","hentry","entry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"ocean-thumb-m":false,"ocean-thumb-ml":false,"ocean-thumb-l":false},"uagb_author_info":{"display_name":"Bryan Higgs","author_link":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/author\/bryan\/"},"uagb_comment_info":0,"uagb_excerpt":"We&#8217;ve actually used exceptions in a few earlier examples, but have delayed talking about them until now. So, let&#8217;s talk about exceptions&#8230; What&#8217;s an Exception? Exceptions are &#8220;exceptional events&#8221; (not necessarily errors!) Events that are outside the normal flow of a program An exception is a subclass of class&nbsp;Exception&nbsp;(actually,&nbsp;Throwable, but more on that later) An&hellip;","_links":{"self":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/75","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/comments?post=75"}],"version-history":[{"count":4,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/75\/revisions"}],"predecessor-version":[{"id":1323,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/75\/revisions\/1323"}],"up":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/34"}],"wp:attachment":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/media?parent=75"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}