Java finally blocks usees or limitations.
YouTube Video >>
- Java finally block is a block that is used to execute important codes such as closing connection, stream, etc.
- Java finally block is always executed whether an exception is handled or not.
- Java finally blocks follows try or catch block.
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
=====================================================================
Limitations:-
Note: The final block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
check Code:
package interviewQuestion;
public class FinallyBlockUseAndLimitation {
public static void main(String[] args) {
System.out.println("Before Exit");
// program exits by calling System.exit()
System.exit(0);
try {
int data = 25 / 0;
System.out.println(data);
}
catch (NullPointerException e) {
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
System.out.println("Without Exit");
}
}