JavaException handling

What is an exception

What is an exception?

At runtime, an unwanted or unexpected event called an exception may occur. An exception interrupts the normal execution of a program. To avoid it, the developer must take additional measures to handle the exception. By handling it we can provide a meaningful message to the user about the error that arose.

When exceptions occur

There are a lot of situations that can cause an exception. Here are some of the situations:
  • zero division attempt (n / 0);
  • passed an incorrect argument to a method;
  • the target file is not found;
  • network interaction problem;
  • and many others.

All exceptions are presented by different classes and have meaningful names. This helps programmers figure out why errors appeared in a program.

ArithmeticException

Suppose you write a program that reads two integers from the standard input and then outputs the result of the integer division of the first number by the second one. Look at the code below.

import java.util.Scanner;

public class ArithmeticExceptionDemo {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int a = scanner.nextInt();
        int b = scanner.nextInt();

        System.out.println(a / b); // it may throw an exception
    }
}

If a user passes 9 and 3 to the input, the program outputs 3. But if the second number is zero, the code throws an exception because of division by zero.

Here is the message:

Exception in thread "main" java.lang.ArithmeticException: / by zero
  at org.artb.exceptions.ArithmeticExceptionDemo.main(ArithmeticExceptionDemo.java:14)

As you can see, the program fails with the java.lang.ArithmeticException. This output is not very meaningful for users of the program.

To avoid the exception, we can check the value before the division, and, if the value is zero, print a message. If the second number is zero, the program shouldn't throw any exceptions, but it should output the string "Division by zero!".

Here is another version of the program.

import java.util.Scanner;

public class ArithmeticExceptionDemo {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int a = scanner.nextInt();
        int b = scanner.nextInt();

        if (b == 0) {
            System.out.println("Division by zero!");
        } else {
            System.out.println(a / b);
        }
    }
}

1) The first input example:

8 4

The result is:

2

2) The second input example:

3 0

The result is:

Division by zero!

As you can see, the code above does not throw an exception. Additionally, it prints a user-friendly message instead of the standard message.

NumberFormatException

Another situation is when you are trying to convert a string to an integer number. If the string has an unsuitable format, the code will throw an exception.

The following program should read a number from the standard input, and then output the number that follows it.

import java.util.Scanner;

public class NumberFormatExceptionDemo {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        int number = Integer.parseInt(input); // it may throw an exception
        System.out.println(number + 1);
    }
}

It works pretty well if the input line is a correct integer number. But if the input is not correct, the program will fail:

Exception in thread "main" java.lang.NumberFormatException: For input string: "121a"
  at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.base/java.lang.Integer.parseInt(Integer.java:652)
  at java.base/java.lang.Integer.parseInt(Integer.java:770)
  at org.artb.exceptions.NumberFormatExceptionDemo.main(NumberFormatExceptionDemo.java:12)

To avoid the exception, it is possible to check the input string using a regular expression and output a warning message if the input is not correct. The following program does this:

import java.util.Scanner;

public class NumberFormatExceptionDemo {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        if (input.matches("\\d+")) { // it checks the input line contains only digits
            int number = Integer.parseInt(input);
            System.out.println(number + 1);
        } else {
            System.out.println("Incorrect number: " + input);
        }
    }
}

If the input line is "121a", the program will not stop, and it will print the message:

Incorrect number: 121a

The IndexOutOfBoundsException

There are two kinds of the IndexOutOfBoundsException:
  • ArrayIndexOutOfBoundsException
  • StringIndexOutOfBoundsException

They appear after trying to access a non-existent element of an array or a string.

1) ArrayIndexOutOfBoundsException

Here is an example:


int[] array = { 1, 2, 3 }; // an array of integers
int n1 = array[2]; // the last element of the array is 3
int n2 = array[3]; // ArrayIndexOutOfBoundsException

In the code above, the ArrayIndexOutOfBoundException occurs because the last element of the array has an index of 2.

2) StringIndexOutOfBoundsException

Here is another example:

String s = "123";

char ch = s.charAt(4); // StringIndexOutOfBoundsException 

In this code, the StringIndexOutOfBoundsException happens.

Avoiding ArrayIndexOutOfBoundsException

To prevent this exception and the previous one, we can check that the given index is within the interval [0, length - 1].

Let's write a program displaying an element of the array { 3, 2, 4, 5, 1 } by the given index. if the index is out of bounds the program should print:

"The index is out of bounds."

Here is the program:

public class NoIndexOutOfBoundsExceptions {

    public static void main(String[] args) {

        int[] hardCodedArray = { 3, 2, 4, 5, 1 };

        Scanner scanner = new Scanner(System.in);

        int index = scanner.nextInt();

        if (index < 0 || index > hardCodedArray.length - 1) {
            System.out.println("The index is out of bounds.");
        } else {
            System.out.println(hardCodedArray[index]);
        }
    }
}

Here are inputs and the corresponding outputs of the program:

  • the index is 0, the program outputs "3";
  • the index is 1, the program outputs "2";
  • the index is 4, the program outputs "1";
  • the index is -1, the program outputs "The index is out of bounds.";
  • the index is 5, the program also outputs "The index is out of bounds.".

So, using one conditional statement and the length property we can avoid ArrayIndexOutOfBoundExceptions.

Conclusion

This topic introduced the problem of exceptions that can occur in different situations. Using control statements allows programmers to avoid such exceptions as NPE, IndexOutOfBoundsException, ArithmeticExceptions, and some others. However, this method may not be sufficient for complex applications. In the other topics, a standard, general way to handle any exception will be learned. Advanced exception handling will be learned in other topics.

3 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo