Finally Block in Java
Here are the implementation of Finally block in java language:
// Java code to display the use of finally block in
// exception handling
import java.io.*;
public class ExceptionHandlingExample {
public static void main(String[] args)
{
try {
// Code that may cause an exception
int result = divide(
10, 0); // Attempting to divide by zero
System.out.println(
"Result: "
+ result); // This line won't be executed
}
catch (ArithmeticException e) {
// Handling the exception
System.out.println("An error occurred: "
+ e.getMessage());
}
finally {
// finally block
System.out.println(
"\nFinally block executed, performing cleanup tasks.");
}
}
public static int divide(int num1, int num2)
{
return num1 / num2;
}
}
Output
An error occurred: / by zero Finally block executed, performing cleanup tasks.
Finally Block in Programming
The finally
block in programming, commonly used in languages like Java and C#, is a block of code that is executed regardless of whether an exception is thrown or not. It is typically used in conjunction with a try-catch
block to ensure certain cleanup or finalization tasks are performed, such as closing resources like files or database connections.
Table of Content
- Try-Catch-Finally Block Structure
- Purpose of the Finally Block
- Exception Handling Flow
- Syntax of Finally Block
- Finally Block in Java
- Finally Block in Python
- Applications of Finally Block
- Best Practices of Finally Block
Contact Us