Java: Exception Handling

When the circumstances are normal, the way to control the flow of a program was explored. Now, controlling the flow of a program in the emergence of an error is determined, known as exception handling.

While coding, it is important to estimate potential errors. If a block may cause an error, the try-catch-finally statement must be used to try to handle it. The syntax for the try-catch-finally statement:

try {
    do an action
}
catch (type of error) {
    do another action in case of an error
}
finally {
    do this independent of the try or catch condition being met.
}

While one or more ‘catch’ block can be used, the use of the ‘finally’ block is optional.

Let us look closely at an example. Launch NetBeans and create a new project called errorExample. Substitute the existing code with the following:

import java.util.Scanner;
public class ErrorExample {
    public static void main(String[] args) {
        int numer, denom;
        Scanner input = new Scanner(System.in);
        try {
            System.out.print("Enter the numerator value: ");
            numer = input.nextInt();
            System.out.print("Enter the denominator value: ");
            denom = input.nextInt();
            System.out.println("The value is " + numer/denom);
        }
        catch (Exception e) {
            System.out.println(e.getMessage()); 
        }
        finally {
            System.out.println("---- Example Over ----");
        }
    }
}

This example has the try block and the catch block, along with the finally block is present.

When 8 and 2 are entered, the output will be the following:  

The value is 4
---- Example Over ----

Here, the statements in the try block are executed successfully. That is why the result is displayed. After the try block, the finally block is executed.  

Instead, input 3 and 0, for which the result will be

/ by zero
---- Example Over ----

Here, the try block execution is a failure as a number cannot be divided by zero. Consequently, the catch block is executed. Then, the finally block is executed as well.

When programmers use the catch block, the type of error it must seek can be specified.  Our example involves trying to find general errors. 

Hence, the statement is

catch (Exception e)

Wherein Exception is used to refer to the class that the error belongs.

An exception is a pre-written class in Java, which deals with all types of code errors. Moreover, the getMessage() method informs programmers about the cause of the exception, once they print the error message  

System.out.println(e.getMessage());

The example displays the following error message. 

/ by zero

Specific Errors

The example above has used the Exception class to catch a general error. However, there are several other classes in Java that can help in dealing with more specific errors. Use such classes to perform particular tasks once the error is caught. For example, this can be used to display their custom error messages.

To understand this better, NetBeans is analyzed, and a new project called ErrorExample2 is created. Substitute the existing code with the following code:

import java.util.InputMismatchException; 
import java.util.Scanner;

public class ErrorExample2 {
    public static void main(String[] args) { 
        int a = 0;
        Scanner input = new Scanner(System.in);

        int[] numbers = { 1, 2, 3, 4, 5, 6 }; 
        System.out.print("Type the index of the array: ");

        try {
            a = input.nextInt(); 
            System.out.printf("numbers[%d] = %d%n", a, numbers[a]);
        } 
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Oops! Index does not exist.");
        }
        catch (InputMismatchException e) {
            System.out.println("Oh no. You did not enter an integer.");
        }
        catch (Exception e) {
            System.out.printf(e.getMessage());
        }
    }
}

When 20 is entered, the output is:

Oops! Index does not exist.

When “Bye” is entered, the output is: 

Oh no. You did not enter an integer. 

The first error that is displayed is an ArrayIndexOutOfBoundsException exception, which the first catch block identifies. As is observed, if the user tries to access an array using an index outside the bound, this error is identified.

The second error is an InputMismatchException exception and the second catch block dealt with this one. This exception arose when the input entered does not align with the data type that is expected. Our example led to this error because the input entered was a string while the expected data type was an integer due to the nextInt() method.

In the end, a catch block was added to determine general errors that may have been overlooked. 

Only three exceptions were discussed in this section though there are many more present in Java.

While the InputMismatchExpection class is found in java.util package, which must be imported before usage- the other two exceptions are present in java.lang package, and Java directly imports this package. Programmers need not remember what classes must be imported and what need not, as NetBeans will notify them anytime they must import any package or class.

Throwing Exceptions

The process of throwing exceptions will be discussed now. Previously, errors were caught under pre-defined conditions.

The ArrayIndexOutOfBoundsException has been used to catch users’ errors, trying to access an index that does not exist in the array.  For instance, in the example above, inputting a number greater than 5, or a negative number would result in an error.   

While pre-defined conditions are used to catch errors typically, the provision of defining our own conditions regarding what should result in an error is also present. This process is referred to as throwing an exception.

For example, if coders do not want the users to access the first element, they can define a condition that enables the program to report an error when users enter the number 0.  

For instance, entering 0 as an input in the previous program will delve into this concept. Here, the program runs normally and returns the result normally:

numbers[0] = 1 

However, add this statement to the code: 

if (a == 0)
	throw new ArrayIndexOutOfBoundsException();

Previous example shown with the added if statement below:

import java.util.InputMismatchException; 
import java.util.Scanner;

public class ErrorExample2 {
    public static void main(String[] args) { 
        int a = 0;
        Scanner input = new Scanner(System.in);

        int[] numbers = { 1, 2, 3, 4, 5, 6 }; 
        System.out.print("Type the index of the array: ");

        try {
            a = input.nextInt(); 
            // if statement added here
            if (a == 0)
	            throw new ArrayIndexOutOfBoundsException();
            System.out.printf("numbers[%d] = %d%n", a, numbers[a]);
        } 
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Oops! Index does not exist.");
        }
        catch (InputMismatchException e) {
            System.out.println("Oh no. You did not enter an integer.");
        }
        catch (Exception e) {
            System.out.printf(e.getMessage());
        }
    }
}

Now, if the program is run again and 0 is entered, this block is executed: 

catch(ArrayIndexOutOfBoundsException e)

Because when users type in 0, the condition a == 0

Returns true, leading to the execution of the throw new ArrayIndexOutOfBoundsException();

Consequently, the

catch(ArrayIndexOutOfBoundsException e)

block is executed.

Leave a Reply

%d bloggers like this: