Interview question
How does try-catch-finally work in Java, and when does finally NOT execute? Java में try-catch-finally कैसे काम करता है, और finally कब execute नहीं होता?
Answer
public int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println('Caught: ' + e.getMessage());
return -1;
} finally {
System.out.println('finally always runs'); // runs even with a return above
}
}
divide(10, 2); // prints 'finally always runs', returns 5
divide(10, 0); // prints 'Caught: / by zero', 'finally always runs', returns -1
// finally runs even when try/catch has a return statement
public int example() {
try {
return 1;
} finally {
System.out.println('finally runs before the return completes');
}
}
// Rare cases where finally does NOT execute:
// 1. JVM crashes or is killed (System.exit(), power failure)
public void withExit() {
try {
System.exit(0); // finally will NOT run
} finally {
System.out.println('This never prints');
}
}
// 2. Infinite loop or deadlock inside try block - never reaches finally
// 3. The thread executing try is forcibly killed (Thread.stop() - deprecated)public int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println('Caught: ' + e.getMessage());
return -1;
} finally {
System.out.println('finally हमेशा चलता है');
}
}
divide(10, 2);
divide(10, 0);
public int example() {
try {
return 1;
} finally {
System.out.println('return पूरा होने से पहले finally चलता है');
}
}
// finally न चलने के rare cases:
// 1. JVM crash या System.exit()
public void withExit() {
try {
System.exit(0); // finally नहीं चलेगा
} finally {
System.out.println('यह कभी नहीं print होगा');
}
}
// 2. try में infinite loop
// 3. Thread forcibly kill हो जाएWas this answer clear?