Finally Block – regardless of whether an exception occurs or not finally block will continue to run.
package app_finally;
public class A {
public static void main(String[] args) {
try {
int x = 10/0;
System.out.println(x);
} catch (Exception e) {
}finally {
System.out.println(100);
}
}
}
Output : 100
Example 2
package app_finally;
public class B {
public static void main(String[] args) {
try {
int x=10/2;
System.out.println(x);
System.exit(0);
}
finally {
System.out.println(12);
}
}
}
Output : 5
Finally Block Program in Java
Example 3 – We can also write only try and finally.
package app_finally;
public class B {
public static void main(String[] args) {
try {
int x=10/2;
System.out.println(x);
}
finally {
System.out.println(10);
}
}
}
Output:
5
10
Q.1 – Can we write multi-catch blocks? – Answer is Yes!
package app_finally;
public class MultiCatch {
public static void main(String[] args) {
try {
int x = 10/0;
System.out.println(x);
}
catch(ArithmeticException e) {
System.out.println(1);
}
catch(NullPointerException e) {
System.out.println(2);
}
catch(Exception e) {
}
}
}
Output: 1
You Also Learn –