Home >Java >javaTutorial >Finally in Java
The following article provides an outline on Finally in Java. Finally, is a block of code that 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 the finally block always executes regardless of whether an error occurred in the try block or not. Finally, the 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 that happens in code would be handled gracefully.
ADVERTISEMENT Popular Course in this category FINANCIAL MODELING & VALUATION - Specialization | 51 Course Series | 30 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
try { //block of code that may cause an exception }
catch { //Handling the error occurred in try block }
finally { //code that should always execute }
Here we will throw an error or write an errorounous code that would result in an error and finally block execution.
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 .
And after the try catch finally, block we wrote a block of code outside everything that got printed.
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 an error. The code executed successfully inside the try block, but still, you can see the finally block get executed and printed the message inside.
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 exist):
Output (File Exists):
In the above example, we tried to open a file and read it into the buffer from a file path. If the file exists and we are able to read the file, then no errors would be thrown, and the 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.
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.
Example:
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.
In the conclusion we can reach, it can finally play a very important role in gracefully exiting the program in case of errors. Finally, the block is important when you open a connection or buffered something, and it’s always important to close the connection or file opened. Finally, the 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.
The above is the detailed content of Finally in Java. For more information, please follow other related articles on the PHP Chinese website!