In the previous tutorial, we learned how to handle an exception using throw and throws keywords. Now we will learn about finally block.
finally
is the block that will always get executed irrespective of the fact whether the exception is handled or not.
try () { //code that might produce exception}
catch(Exception e) { //handle exception }
finally { //code that always gets executed }
We can also have finally block without catch block.
try()
{//code that might produce exception}
finally
{//code that always gets executed }
But the problem with the second syntax is that we can not handle the exception since the catch block is missing.
class test {
public static void main(String[] args) {
try {
int x = 10,
y = 2,
z;
Z = x / y;
System.out.println(z);
}
catch(Exception e) {
System.out.println("welcome in catch block");
}
finally() {
System.out.println("Hi, my_name_is_John");
}
}
}
Output:
5
Hi, my_name_is_John
The above code will not go to catch block since no exception arises. Statements of try
and finally
gets executed.
Now let’s see an example where an exception arises.
class test {
public static void main(String[] args) {
try {
int x = 10,
y = 0,
z;
Z = x / y;
System.out.println(z);
}
catch(Exception e) {
System.out.println("welcome to the catch block");
}
finally() {
System.out.println("Hi, my_name_is_John");
}
}
}
Output:
Welcome to the catch block.
Hi, my_name_is_John
Here the exception arises but then also the finally block gets executed. Now, what happens if we write the finally block with try block but without catch block. Let’s see the given example
class test {
public static void main(String[] args) {
try {
int x = 10,
y = 0,
z;
Z = x / y;
System.out.println(z);
}
finally() {
System.out.println("Hi, my_name_is_John");
}
System.out.println("Hello");
}
}
Output:
Hi, my_name_is_John
ArithmeticException: divide by zero
The above code gets terminated abnormally because the exception has not been handled but then also finally block gets executed.
Unlike catch block, we can’t use multiple finally block with one try block.
It might happen sometime that finally block does not get executed. Some of the possible cases are:
finally block is also used for explicitly closing the resources such as connections, files, etc.
Unlike finally, try with resources automatically closes all the running resources which have been initiated by try and catch block.
try (Resource declaration) {
// code that uses the resource
} catch(ExceptionType e1) {
// catch block which handles all the exceptions
}
import java.io.FileReader;
import java.io.IOException;
public class test {
public static void main(String args[]) {
try (FileReader file = new FileReader("d://xyz.txt")) {
int[] a = new int[10];
file.read(a);
for (int c: a)
System.out.println(c);
}
catch(IOException e) {
e.printStackTrace();
}
}
}
In the above code, the FileReader
class automatically gets closed as the try and catch block gets executed.
Some important points regarding try and resource statement
You can also create customized exception class. If you want to create a checked exception, you’ll need to extend the Exception
class, if you want to create the unchecked
or runtime
exception class then you’ll need to extend RuntimeException
class.
import java.util.Scanner;
class AgeLimit extends RuntimeException {
AgeLimit(String s) {
super(s);
}
}
class voting {
public static void main(String[] args) {
int age = 16;
if (age < 18) {
throw new AgeLimit("you are not eligible for voting");
}
else {
System.out.println("you can vote");
}
}
System.out.println("hello");
}
Output:
Exception in thread "main" AgeLimit:you are not eligible for voting.
Above is created an unchecked
exception class by the user which extends the RuntimeException
and its constructor prints the exception that occurs.
With this, we have completed our tutorial of exception handling using five keywords i.e. try
, catch
, finally
, throw
and throws
. Some important points which you need to know about the rules of the declaration of these five keywords are:
Help us improve this content by editing this page on GitHub