Saturday, April 5, 2025

Java finally Block

 Java developers often face tricky questions during interviews, and one common question is:


1. Understanding Try-Catch-Finally

2. Example: Return in Catch Block

public class FinallyExample {
public static int testMethod() {
try {
int result = 10 / 0; // Causes ArithmeticException
return result;
} catch (ArithmeticException e) {
System.out.println("Catch Block Executed");
return 1; // Return statement in catch
} finally {
System.out.println("Finally Block Executed");
}
}
public static void main(String[] args) {
int result = testMethod();
System.out.println("Result: " + result);
}
}

Output

Catch Block Executed
Finally Block Executed
Result: 1

3. Analysis of Output

4. What If Finally Also Has a Return Statement?

public class FinallyWithReturn {
public static int testMethod() {
try {
int result = 10 / 0;
return result;
} catch (ArithmeticException e) {
System.out.println("Catch Block Executed");
return 1;
} finally {
System.out.println("Finally Block Executed");
return 2; // Return in finally
}
}
public static void main(String[] args) {
int result = testMethod();
System.out.println("Result: " + result);
}
}

Output

Catch Block Executed
Finally Block Executed
Result: 2

Explanation

5. Key Takeaways

6. Interview Questions Related to Finally

public class FinallyTest {
public static void main(String[] args) {
System.out.println(test());
}

static int test() {
try {
return 1;
} finally {
return 2;
}
}
}


7. Conclusion

No comments:

Post a Comment

CompletableFuture

  Welcome back to  our concurrency series ! In our first discussion, we likely touched on the traditional models of threading. Today, we’re ...