CodingBison

Let us take a look at the exception class hierarchy, understanding the hierarchy is important in order to look into the remaining topics of Exception Handling. The following figure shows the "Throwable" class that is the super class of all the exception and error classes. Also, the Exception class itself has 2 types (Runtime exceptions and IO exceptions) of subclasses under it. All the IO exceptions are called checked exceptions because compile throws an error if there are not handled. Runtime exception also called unchecked exceptions are handled by the compiler during the runtime. We will discuss more about unchecked and checked exceptions in the next section: Understanding Throw/Throws.



Figure: Exception Hierarchy

In general a super class can catch all the exceptions of its sub classes. So, when we have multiple catch blocks for a given try statement, we should place the sub-class (or specific Exception) first and then place the super-class (aka the Exception class). Accordingly, let us see an example that demonstrates this behavior. The following figure has a try block with two catch blocks, Catch Block-1 (ArithmeticException) and Catch Block-2 (Exception). Thus, if there is any arithmetic exception in the try block, then Catch Block-1 would be the one to catch it. For any other type of exceptions, it would be catch Block-2 that would handle them.



Figure: Exception Hierarchy with Multiple Catch Blocks

We should keep in mind that the order of the catch blocks is important. If a super class exception catch block is placed ahead of the sub class exception catch block, then the compiler would not be happy and would throw an error. Thus, the following would not compile.



Figure: Exception Hierarchy with Multiple Catch Blocks -- Not Allowed





comments powered by Disqus