Introduction to Finally in Java
The following article provides an outline on Finally in Java. Finally, is a block of code which is used along with try and catch. Finally contains the block of code that must be executed whether an exception occurs or not. The statements written inside finally block always executes regardless of whether an error occurred in try block or not. Finally block is good for closing files or a database connection that makes sure that you don’t get any memory error due to open file or database error due to open connection or max connection error. It also makes sure that any error happens in code that would be handled gracefully.
Syntax:
try {
//block of code that may cause an exception
}
catch {
//Handling the error occurred in try block
}
finally {
//code that should always execute
}<>
How Finally works in Java?
Here we will throw error or write errorounous code that would result in error and execution of finally block.
Code:
class ExampleFinally
{
public static void main(String args[]) {
try{
int result = 1/0;
System.out.println(result);
catch(ArithmeticException e){
System.out.println("Divide by Zero Error");
}
/* Finally block will always execute
* even when we have created an error
Block */
finally{
System.out.println("Gracefully Handling Error in Finally");
}
System.out.println("Execution complete out of Try Catch Finally block");
}
}
Output:
Explanation:
In the above program we have divided a number from zero which we already .
- Gracefully Handling Error in Finally.
And after the try catch finally block we wrote a block of code outside everything that got printed.
4.8 (8,040 ratings)
View Course
- Execution complete out of Try Catch Finally block.
Another example we would see where no exception would occur inside try-catch-finally block and see what happens.
Code:
class ExampleFinally
{
public static void main(String args[]) {
try
{ int result = 100/10;
System.out.println(result);
System.out.println("try code block");
}
catch (Exception e)
{
System.out.println("catch code block");
}
finally
{
System.out.println("finally code block");
}
}
}
Output:
Explanation:
In the above program we didn’t write any code that can cause error. The code executed successfully inside try block but still you can see the finally block get executed and printed the message inside.
- finally code block
Finally Block Usage in Java Program
Opening a file for reading or writing requires opening a file then buffer the stream and we should make sure to close the opened file so that we won’t get any file handling, IO or disk errors.
Code:
import java.io.*;
public class ReadingFromFile
{
public static void main(String[] args)throws Exception
{
FileReader fr = null;
try {
fr = new FileReader("/Users/cdp/Documents/testing/python virtual/java/myfile.txt");<>
System.out.println("Opening the file");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
System.out.println("Closing the file ");
fr.close();
} catch (IOException e) {
System.out.println("unrecoverable Error occurred");
e.printStackTrace();
}
}
System.out.println("Exiting Finally block");
}
}
}
Output ( File doesn’t exists):
Output (File Exists):
In the above example we tried to open a file and read into buffer from a file path. If the file exists and we are able to read the file then no errors would be thrown and file buffer would get closed in finally block if it’s not null. Even if there is an error in reading the file let say because of some permission then also in finally block the file would get closed.
Significance
- Finally block must be always associated with a try block, we can not write use finally block without an try block. The statements which you write inside finally block would get executed, always not dependent on try block code whether error occurs or not.
- Finally block is not a mandatory block we can write the try and catch block without finally block. Let’s say we just want to catch errors for any user input where input is buggy.
- In a case where there isn’t any error occured still finally the block will be executed. If there is any error then first catch block is executed then finally.
- All the exceptions have the same behaviour in finally block. The block would be executed normally for all the exceptions.
- Finally the block will execute even if there is a break, return or continue statement in the try block.
When Finally won’t Execute ?
Till now we have seen when and how finally block would get executed.
But there can be certain scenarios where finally the block won’t get executed.
- There could be a thread getting executed it most likely to be the main thread where program execution is happening and abruptly it dies, then the finally block won’t be getting executed.
- If in the try or catch block we have used System class with the exit method that is System.exit() then the whole system would exit and no control will be transferred to the next block of code.
- If finally only throws an exception then the program would not exit gracefully but exit abruptly.
Example:
span data-contrast="auto">import java.io.*;
public class ReadingFromFile
{
public static void main(String[] args)throws Exception
{
FileReader fr = null;
try {
fr = new FileReader("/Users/cdp/Documents/testing/python virtual/java/myfile.txt");
System.out.println("Opening the file");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
System.exit(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
System.out.println("Closing the file ");
fr.close();
} catch (IOException e) {
System.out.println("unrecoverable Error occurred");
e.printStackTrace();
}
}
System.out.println("Exiting Finally block");
}
}
}
Output:
In the above example we have used System.exit in the try block after reading the file and it gets executed. If the System.exit gets executed without any exception then there won’t be any control transfer to the finally block. However in the case of an exception occuring before the System.exit then finally block would surely get executed.
Conclusion
In the conclusion we can reach is that finally can play an very important role in gracefully exiting the program in case of errors. Finally block is important when you open a connection or buffered something and it’s always important to close the connection or file opened. Finally block would even execute if there is an error or no error in the try block code. Finally blocks are not mandatory but are useful in some situations.
Recommended Articles
This is a guide to Finally in Java. Here we discuss the introduction to finally in Java with examples for the usage in Java Program. You may also have a look at the following articles to learn more –