Back to: Java Tutorials
In Java, the finally
block is used in conjunction with the try
and catch
blocks to ensure that a section of code is executed, regardless of whether an exception is thrown or not.
The basic syntax of a try
–catch
–finally
block is as follows:
try {
// code that might throw an exception
} catch (Exception e) {
// code to handle the exception
} finally {
// code to run regardless of whether an exception was thrown
}
Here, the try
block contains the code that might throw an exception, the catch
block contains the code to handle the exception, and the finally
block contains the code that will be executed regardless of whether an exception is thrown or not.
The finally
block is often used to perform cleanup tasks, such as closing files or releasing resources, that must be performed regardless of whether an exception is thrown. For example, consider the following code that reads from a file:
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream("file.txt");
// code to read from the file
} catch (FileNotFoundException e) {
// code to handle the exception
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// code to handle the exception
}
}
}
Here, the try
block attempts to open the file “file.txt” and read from it. If a FileNotFoundException
is thrown, the catch
block handles it. Finally, the finally
block closes the file, regardless of whether an exception was thrown or not.
It is important to note that the code in the finally
block will be executed even if a return
statement is encountered in the try
or catch
blocks. For example:
public int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
return -1;
} finally {
System.out.println("Finally block executed.");
}
}
In this example, the finally
block will be executed even if an ArithmeticException
is thrown and the code in the catch
block is executed, or if the code in the try
block returns a value.
Follow us on social media
Follow Author