Cracking The Secrets of Try Catch Finally In Java

Cracking The Secrets of Try Catch Finally In Java

try catch finally in Java

Java uses try catch finally block to handle exception. Lets explore the try catch finally blocks in details.

Java try block

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:

try {
    code which might throw an exception
}
catch and finally blocks . . .

In the previous example we have seen the database connection code which was throwing an exception so in this case what we will do is we will keep that database connection code in try block so in case if the database is down or if the credentials are wrong then that piece of code will throw an exception saying that the we cannot connect to the database.

So thats why we use try blocks. we keep the code in try block off which we suspect that it might throw an exception or it might lead to an abnormal condition.

Lets take another example and see how can we use try block.

Lets open a file from our local system. We might get some exception while reading a file like

  1. File might not be available in the system.
  2. User might not have permission to open that file
  3. and so on……

So we can put this code inside the try block :). Lets write the code for it.

import java.io.File;
import java.io.FileReader;

public class TryCatchFinallyExample {
  public static void main(String[] args) {
      System.out.println("Reading a sample file");
      try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String st;
        while ((st = br.readLine()) != null) {
          System.out.println(st);
        }
      }
  }
}

Okay, but still we are not good… Why? Java is complaining below error

Unhandled exception: java.io.FileNotFoundException

Its because you will have to catch that exception or abnormal condition and tell java what to do? Like what to do if the file is not available. So lets learn catch block in java.


Java catch block

Java catch block is used to handle an Exception by declaring the type of exception within the parameter. We can write our code to handle that exception like in our example if the file is not found then in that case we can show an error to the user that the file is not available.

Let resolve our compilation issue by adding a catch block to it.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;

public class TryCatchFinallyExample {

  static List<String> list = null;

  public static void main(String[] args) {
    System.out.println("Reading a sample file");
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String st;
        while ((st = br.readLine()) != null) {
          System.out.println(st);
          list.add(st);
        }

      br.close();
    } catch (Exception e) {
      System.out.println("File is not available at that location");
      e.printStackTrace();
    }
  }
}

So now when you run this [program you will get below output if the file is not available at that location.

File is not available at that location

Reading a sample file
File is not available at that location
java.io.FileNotFoundException: sample1.txt (No such file or directory)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileReader.<init>(FileReader.java:72)
	at com.americanexpress.bipapi.features.service.TryCatchFinallyExample.main(TryCatchFinallyExample.java:16)

Process finished with exit code 0

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.

Here the above code will throw an Exception and our code will catch that exception inside the catch Block and will print “File is not available at that location”.


Java finally block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a returncontinue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

In the catch block code if the file is available then it will open that file and print its contents.

ahhhh waittt….. we are not closing the file. We should always close the resources which we open in java. Lets write some code to close the file.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;

public class TryCatchFinallyExample {

  static List<String> list = null;

  public static void main(String[] args) {
    System.out.println("Reading a sample file");
    try {
      File file = new File("sample1.txt");
      BufferedReader br = new BufferedReader(new FileReader(file));
      System.out.println(br.readLine());
      list.add(br.readLine());
      br.close();
    } catch (Exception e) {
      System.out.println("File is not available at that location");
      e.printStackTrace();
    } finally {
      System.out.println("I will always execute");
    }
  }
}

Here we are closing our BufferedReader with br.close(); line but when we run this program we are getting below NullPointerException. Its because we have initialised at least with null. Such scenarios can happen in your execution of the program where some exception or abnormal condition might happen before closing that resource and the downside of that will be we won’t be able to close resource. thats the problem of closing the resource in try block. and thats why finally block came into picture.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class TryCatchFinallyExample {

  static List<String> list = null;

  public static void main(String[] args) throws IOException {
    System.out.println("Reading a sample file");
    BufferedReader br = null;
    try {
      File file = new File("sample1.txt");
       br = new BufferedReader(new FileReader(file));
      System.out.println(br.readLine());
      list.add(br.readLine());
      
    } catch (Exception e) {
      System.out.println("Something went wrong....");
      e.printStackTrace();
    } finally {
      System.out.println("I will always execute and thats why I am closing all opened resources");
      br.close();
    }
  }
}

Now the program will run and open the file and print its content but when it tries to add the file content to the list the program will throw NullPointerException. But we have moved our resource closing code into finally block so in this case java will close that resource. Thats how finally block has saved us 🙂 The output of above program will be as follow –

Reading a sample file
Learn Exception handling
Something went wrong...
I will always execute and thats why I am closing all opened resources
java.lang.NullPointerException
	at com.onlyfullstack.TryCatchFinallyExample.main(TryCatchFinallyExample.java:20)

Process finished with exit code 0

When finally is executed?

  1. Whenever you return anything from the try block
  2. When any exception occurs in try block or in catch block
  3. In short finally block always gets executed except developer writes System.exit(0) code in try block.

Referred Resources –

https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html