i

JAVA Complete Course

Learning exception handling, try-catch, multiple catch clauses

One of the easiest way to deal with and handle exceptions is try-catch block. Until we move on the concrete examples, let’s shortly say this process. Try-Catch block is undividable block, we cannot have only try, or only catch. The allowed pairs are: Try-Catch, Try-Finally (We will touch finally block later), Try-Catch-Finally. In try block we write the code snippet which might cause an abnormal situation, and in catch parameter we define the expected exception which might happen in try and then in its block we write the logic how it can be handled. One nuance is that in catch parameter we have to be careful of exception hierarchy because we give parameter any exception class in catch but the actual exception will be on higher level in exception hierarchy, our code will never reach the actual catch block, but in other way if we give to catch block as a parameter any exception, then during any lower exception our code will reach the catch block. One more thing until we move on the actual examples is that with one try we can have multiple catch clauses but here the order of catch clauses makes sense. The first always must be the most specific exception class. We will cover this part also in examples.

Simple Try-Catch example (Unchecked Exception):

Try-Catch example with more specific exception (Unchecked exception)

Let’s prove that as we mentioned, we are not obliged to handle unchecked exceptions. I will remove the try-catch block and we will see that compiler won’t complain about this and it won’t reach the System.out.println() method because of exception

Checked exception example: Let’s prove that we must deal with checked exceptions.

 

If we put it in try-catch then everything is fine:

Let’s now revisit the multiple catch clauses example.

Let’s now reorder the operations in try block and see what will happen:

Now let’s revisit an example to prove that in case of multiple catch clauses first always must be more specific (Lower level in exception hierarchy)

As ArrayIndexOutOfBoundException is child of RuntimeException compiler complains that the code will never reach ArrayIndexOutOfBoundException block.

We have in Java option to combine few exceptions in one catch clause and let’s revisit this example to cover this topic fully: