Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Java Exception Handling: Try Catch Finally

1. Introduction to Java Exception

When application crashes the JVM excludes it from any further execution. This means application halts abruptly. In Java Exception Handling is useful to avoid application crashes. Exception handles error condition and takes a safer path in the execution flow. The exception also makes code more readable as the error handling code stays in a separate section from the normal business logic code. In this example, we will see how to handle exception using Try & Catch blocks. We will also see the role of Finally block.

2. Separating Error Handler

With exception handling, we can separate the error handling code to separate section. We can get more insight about it by looking at the picture below:

Separating Error Handling Code
Separating Error Handling Code

Above we can see two styles of handling the errors. On the left side, we have 3 code snippet which performs specific operation. After each operation, we have error handling code. This is marked as 1,2,3. Here, you can see the error handling code is mixing with the business logic.

But on the right-hand side, the error handling code stays in a separate section. The marking 4 is the code we keep in the exception handling section. In java, we can do this via catch block. The block diagram on the right-hand side shows the business logic is neat and clear as it not mixing with the error handling code snippets.

3. Role of Try & Catch Blocks in Java Exception

In java, we use try & catch blocks to handle the exceptions. Now, have a look at the below depiction:

Java Try and Catch Blocks
Java Try and Catch Blocks

In the above picture, we can see a Try block pairs with the Batch block. The catch black is the one which handles exception. In the above example, the catch block is receiving an object called Exception. So, we can say that a catch block can handle a specific exception type. One can have multiple catch blocks to handle multiple exception types.

In the above example, we handle the exception raised in the try block inside the catch block. The handler gets an Exception object and from where it can get details about the exception cause. We know that Object is the base class for all the classes in Java. Likewise, the Exception is the base class for other specific exceptions. So, in the above code we are handing the exception with more generalized Exception class instance ex. Java provides more specialized Exception classes to handle the Exception with more granular details.

4. Unhandled Exceptions

The application crashes when the code does not handle the Exception. We call this case as Unhandled Exception. In case of a crash, OS does not agree to execute any instruction from the program. In Java World, the JVM (Java Virtual Machine) removes the program and does not execute any instructions. Now, we will see an example for the Unhandled Exception in Java. Have a look at the below piece of code:

JVM raises an exception when it tries to execute the expression x/0. Division by zero is undefined, and it is a program error. When there is no handler code for this expression, JVM removes the program from further execution. The application user will report this as a program error or crash. In JVM’s point of view, it just encountered with an exception with no handler code for it. It sees this as an Unhandled exception and hence stop executing the further instructions. A developer can see this unhandled exception in the screen, which is here in the below picture:

Un-Handled Exception in Console Window of Eclipse
Un-Handled Exception in Console Window of Eclipse

5. Handling Java Exception

To handle exception, we must place the code in suspect within the try block. When an exception rises, the try block will hand-over the exception to the matching catch block.  Below is the sample code which handles the exception in the catch block:

Java Try..Catch Example
Java Try..Catch Example

Here, we know that the expression x/0 will raise an Exception and to handle that we place three statements inside the try block. When run-time gets an exception, it moves the flow control directly to the catch block. The catch block here handles the exception with correct exception type. The type here is ArithmeticException and raised exception matches with this type.  Also note, when exception is raised the control does not execute any raining statement in the try block which follows the exception raising statement. In our case, the runtime skips the println statement because of the exception handler.

6. Finally Block

When the code raises the exception, the flow moves to catch block skipping remaining statements in catch block. So, if we want to have some clean-up code like closing the file handle, closing the DB connection, etc. where will we do it? Can we do it in the catch blocks? Yes? Probably that is not the right answer. Because there will be a possibility of multiple catch blocks which we study later. To avoid clean-up code redundancy, Java provides Finally block.

The Finally Block as the name suggests has the code which will run at-last. The Finally Block accompanies the try & catch block. Whether or not the code flow enters the try block, we can guarantee that it will enter the finally block. Have a look at the below code snippet:

Finally Block Example
Finally Block Example

In the above code, JVM executes the Finally block whether it encounters the exception in the try block or not. Once the code flow enters inside the try block, it will always execute the code in the finally block. So, there are two code flow orders:

  • In case of Exception: Try Block -> Catch Block -> Finally Block.
  • In case of smooth flow: Try Block -> Finally Block.

7. Code Reference

7.1 Application Crash

7.2 Try Catch Finally – Java Example

8. Watch This Example as Video

Java Exception Handling Explained

Categories: Java

Tags: , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.