Introduction
Finally block in java contains all the crucial statements that must be executed whether exception occurs or not. The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc. The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
JavaFlowchart of finally block in java
Points To Remember While Using Finally Block in Java
- A catch clause cannot exist without a try statement.
- It is not compulsory to have finally clauses whenever a try/catch block is present.
- The try block cannot be present without either catch clause or finally clause.
- Any code cannot be present in between the try, catch, finally blocks.
- finally block is not executed in case exit() method is called before finally block or a fatal error occurs in program execution.
- finally block is executed even method returns a value before finally block.
Why Java Finally Block Used?
- Java finally block can be used for clean-up (closing) the connections, files opened, streams, etc. those must be closed before exiting the program.
- It can also be used to print some final information.
Example 1
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("Finally block executed");
}
}
}
JavaOutput
Error: Division by zero
Finally block executed
JavaExample 2
public class FinallyReturnValue {
public static void main(String[] args) {
System.out.println(testFinally());
}
public static int testFinally() {
try {
return 1;
} catch (Exception e) {
return 2;
} finally {
return 3;
}
}
}
JavaOutput
3
JavaExample 3
import java.io.*;
public class FinallyResourceCleanup {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
System.out.println("Error closing reader: " + e.getMessage());
}
System.out.println("Finally block executed");
}
}
}
JavaOutput
Contents of example.txt
Finally block executed
JavaConclusion
In conclusion, the finally
block in Java is a fundamental feature used in exception handling. It provides a mechanism to execute essential code that must be run whether an exception occurs or not. Key points regarding the finally
block include:
- Execution Guarantee: The code within the
finally
block is guaranteed to execute, irrespective of whether an exception is thrown or not. This ensures critical cleanup tasks or resource deallocation occurs reliably, enhancing the robustness of the program. - Useful for Resource Management:
finally
blocks are commonly used for releasing resources such as file handles, database connections, or network sockets. This ensures that resources are properly released, preventing potential resource leaks and improving system stability. - Combination with Try-Catch Blocks:
finally
blocks are often used in conjunction withtry-catch
blocks. Whiletry-catch
handles exceptions,finally
ensures that cleanup operations are performed regardless of whether an exception is caught or not. - Potential Pitfalls: While
finally
blocks offer valuable functionality, developers should be cautious of potential pitfalls, such as inadvertently masking exceptions thrown within thefinally
block, which can lead to unexpected behavior.
Overall, the finally
block plays a crucial role in exception handling and resource management in Java, contributing to the development of robust and reliable applications.
Frequently Asked Questions
The finally block in Java is used to define code that must be executed regardless of whether an exception occurs in the preceding try block or not. It ensures that essential cleanup tasks are performed, such as releasing resources or closing connections, contributing to the overall robustness of the program.
No, a finally block must always be associated with a preceding try block. It cannot exist independently. The finally block provides a mechanism to define cleanup code that executes whether an exception occurs or not within the associated try block.
If an exception is thrown from within the finally block, it will override any exception thrown in the preceding try block or catch block. However, the original exception will not be lost; it will still be accessible through the Throwable object thrown in the finally block.