Home >Java >javaTutorial >Finally in Java

Finally in Java

WBOY
WBOYOriginal
2024-08-30 16:15:28623browse

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 Tests

Start 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
}

How Finally works in Java?

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:

Finally in Java

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.

  • 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:

Finally in Java

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.

  • 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 exist):

Finally in Java

Output (File Exists):

Finally in Java

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.

Significance

  • Finally, the block must always be associated with a try block; we can not write use finally block without a try block. The statements which you write inside finally block would get executed, always not dependent on try block code whether an error occurs or not.
  • Finally, the 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 the first catch block is executed, then finally.
  • All the exceptions have the same behaviour in the 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 is 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:

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:

Finally in Java

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, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Event Handling in JavaNext article:Event Handling in Java