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
- 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
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
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at org.artb.exceptions.ArithmeticExceptionDemo.main(ArithmeticExceptionDemo.java:14)
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!".
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);
}
}
}
8 4
2
3 0
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
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);
}
}
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);
}
}
}
Incorrect number: 121a
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.