Before we start to know about try Catch Finally, we should know about Exceptions and its handling in Java.

In Java, according to Oracle’s Java documentation, An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

For example, If a program is trying to read/write a file from a location, and if the file is not found or not accessible then we get FileNotFoundException exception.

Another example where most of the developer face issue in real time is NullPointerException also referred as NPE.One scenario when we get NPE is, when we try to updated an object which is null, then Java will through NPE. That’s why it is recommended to add null checks before updating any Java Object.

These are some of the exceptions which we face in our day to day life. There are many other exceptions available, which are out of the scope for this post. So, the main idea is when a program is being executed and when unintended event happens, Java will through Exception. When the exceptions are thrown, we may get issues like program halts or in Web applications user will see stack trace of an exception, which end users don’r know about.

To avoid these issues, we can handle Exceptions programmatically and if any unexpected event happens, then we can show the meaning full messages to users and log the required details for developer to debug.

This can be done by the trio called “try-Catch-Finally”.

These 3 try, catch and Finally are the building blocks of Exceptions handling. Let us see on by one

Try Block

Try block is the place where we have actual logic implemented. For example, File handling or updating the Objects and so on…

Try block is the place where Exceptions get generated.

When we suspect that particular code may have chance of throwing the Exception we surround that code with try block

Below is the example of try block

Private void printStringLength(String name){
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
}

As we see in above example, first line in try block is trying to get the length of a String. Here if String is not empty, then everything works fine. But what if String is null, User will get unexceptced NPE error.

To avoid this, we need to surround the code where we suspect there is a chance of exception, with try block like below

private void printStringLength(String name){
       try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
     }
}

catch block

catch block are where we handle the Exception thrown from try block. Code written in catch block are executed only when there is an Exception raised in try block, otherwise catch block is skipped.

In General when we developing application, we don’t want to show the user error messages which are not user friendly like “java.lang.NullPointerException” with some stack trace. Instead we want to show some meaningful information like “Given Name is empty” and then log the stack trace for developer to debug.

Above process of displaying meaningfull message to user/client is handled in catch block.

Below example of catch block

private void printStringLength(String name){
        try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
        }catch(Exception e){
           System.out.println(“ Exception occurred while getting length“);
        }
}

finally block

Finally block, as the name suggest, is executed after executing try and/or catch blocks.

Usually we use finally if we want to perform some operation irrespective of whether an exception occurred or not.

For example,

We want to close a DB connection after performing some task in try block, but If any exception occurred there is a chance that rest of the code doesn’t execute, in that scenario we want to close connection. To close the connection, we can put the code in finally block.

Finally block make sure whatever code inside is executed 100% whether an exception occurs or not.

private void printStringLength(String name){
        try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
        }catch(Exception e){
            System.out.println(“Exception occurred while getting length “);
        }finally{
            System.out.println(“In Finally “)
        }
}


Above is just a brief idea on how try catch finally works, still there is a vast amount of information left, which can be found in Oracle java docs and other places.