If you have written finally block along with try-catch block, then finally block always gets executed.
public class TryCatchFinallyDemo {
public static void main(String[] args) {
int a=10;
int b=0;
int c=5;
try {
System.out.println(a/b); //Exception occurs
System.out.println(a/c); //Exception does not occur
}
catch(Exception e)
{
System.out.println("It is not valid to divide any number by zero");
}
finally {
System.out.println("The code ends here! Happy Learning!"); //finally block always executes
}
}
}
Output will be:
When exception occurs:
It is not valid to divide any number by zero
The code ends here! Happy Learning!
When exception does not occur:
2
The code ends here! Happy Learning!
The finally block does not get executed only when:
-
If the JVm crashes
-
if you invoke System.exit()