Java

Java exception handling

When the normal flow of the program execution interrupts for any error, then it is called an exception. This type of event can be handled by using a try-catch-finally block. An exception is an object that is used to catch the error and run the statement based on the error condition that is called exception handling. Mainly two types of error are handled by exception handling. These are compiled time errors and run-time errors. The run-time errors are handled by exception handling. How you can handle exceptions in Java is explained in this tutorial.

Syntax:

The syntax of the try-catch-finally block is given below.

try {
  statement 1..N
}
catch (ExceptiontType var) {

  statement 1..N
}
finally {

  statement 1..N

}

Here, if an exception occurs within the try block, then the exception will be thrown to the catch block, and the finally block is optional here. The code of the finally block executes whether an exception occurs or not.

Example-1: Exception handling with a single catch block

The following example shows the use of exception handling using a single catch block. A filename will be taken as input and create an object of BufferedReader to open a file for reading. If the filename exists, then the content of the file will be read line by line and printed. If the file does not exist, then an exception will be generated, and an error message will be printed.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class except1 {

    public static void main(String[] args) {
       
        // Create a Scanner object
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the filename : ");
               
        // Take string data from the user
        String FileName = in.next();
       
        try {
            //Create a reader object
            BufferedReader reader = new BufferedReader(new FileReader(FileName));
            //Read the first line if the file exists
            String line = reader.readLine();
            while (line != null) {
                //Print the line
                System.out.println(line);
                //Read the next line
                line = reader.readLine();
            }
           
            //Close the reader object
            reader.close();
            //Close the scanner object
            in.close();
           
        } catch (IOException e) {
            //Print the error message
            System.out.println("File does not exist");
        }
   }
}

Output:

In the following output,  ‘hello.txt’ is given as the filename that does not exist. So the following message is printed.

Next time, file1.txt is given as filename that exists, and the output shows the content of the file.

Example-2: Exception handling with multiple catch block

How you can use multiple catch blocks to handle multiple exceptions is shown in the following example. Here, three catch blocks are declared. The first catch block will catch the arithmetic error when any illogical arithmetic operation is done. The second catch bock will catch the out of range error of array when an array index value will be tried to read that does not exist. The third catch block will catch the numeric value error when any character or string value is given as an array value. In the code, an array with four indexes is declared and initialized with the integer values that will be taken from the user. The array values are printed using a loop. A division operation is done at the end of the try block.

import java.util.Scanner;

public class except2 {

    public static void main(String[] args)
    {
        try
        {        
              //Declare a numeric array
              int num_arr[] = new int[4];
             
              //Create a Scanner object
              Scanner in = new Scanner(System.in);
             
              System.out.println("Enter four numbers:");
             
              //Iterate the loop four times
              for (int i = 0; i < 4; i++) {
                    //Input number
                    int n = in.nextInt();
                    //Assign value to array
                    num_arr[i] = n;
              }
             
              System.out.println("Array values are:");
             
              //Iterate the loop five times
              for (int i = 0; i < 4; i++) {
                  //Print the array values
                  System.out.println(num_arr[i]);      
              }
             
              //Divide and print the value
              int num = 50/0;
              System.out.print(num);
             
              //Close the scanner object
              in.close();
        }
        catch(ArithmeticException e)  
          {  
             System.out.println("No number is divisible by 0");  
          }    
        catch(ArrayIndexOutOfBoundsException e)  
        {  
             System.out.println("Out of array index value occurred");  
        }    
        catch(Exception e)  
        {  
             System.out.println("Number value is not given");  
        }              
    }
}

Output:

The following output shows that array values are inserted and printed properly, but the third catch block is executed because 50 is divided by 0, which is an error.

The program is executed for the second time. When a string value is given as an array value, then the second exception is generated, and the statement of the second catch block is executed.

Example-3: Exception handling with try-catch-finally block

The use of finally block with the try-catch block is shown in the following example. The code of finally block executes if an exception occurs or not. In the code, an integer value will be taken from the user. If the user gives any string value, then InputMismatchException

will generate and print the message from the catch block. Scanner object will be closed in the finally block if the exception generates or not.

import java.util.Scanner;
import java.util.InputMismatchException;
public class except3 {

    public static void main(String[] args) {
       
        //Create a Scanner object
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number : ");
       
        try {
           
            //Take string data from the user
            int number = in.nextInt();
                  //Print the number
                  System.out.println("The value of number = " + number);
           
            } catch(InputMismatchException e) {
                 //Print error message
                  System.out.println("String value is not accepted.");
            }
            finally {
                 //Close the scanner object
                in.close();
                  System.out.println("Terminated from the program");
            }
      }
}

Output:

78 is given as input value in the following output after executing the code. So, no exception is generated here. The message from the finally block is printed later.

Next, hello is given as input after executing the code that is a string. So, the exception is generated, and the error message from the catch block is printed. The message from the finally block is printed later.

Conclusion:

Exception handling is a very important and useful feature of any programming language that can be used to hide the real error message from the user and provide the human-readable error message for the user to understand the error properly. This tutorial helps the user to learn different ways of applying exception handling in Java and make their code more appropriate.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.