Examples of Exceptions


🙋 Need help? Ask an expert now!

Let's take time to learn about some of the most common exceptions, what each one means, and how to handle them as you start your writing your own code. In order for you to try and test the exception causing scenarios, use the try{} and catch{} blocks in each scenario.

Have you experienced the "ArrayIndexOutOfBoundsException" before? It is thrown when you try to access an array through an index that doesn't exist in the array. For example, calling an index that is less than 0 or greater than or equal to the length of the array will cause this error. Take a look at the code below.
package exlcode;

public class ArrayIndexOutOfBoundsExample {

  public static int[] exampleVariableOne = new int[10];

  public static void main(String[] args) {
    try {
      // ArrayIndexOutOfBoundsException will be thrown because
      // exampleVariableOne only has a length of 10
      exampleVariableOne[11] = 9;
      System.out.println("Array index is valid");
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index is out of bounds");

The program above tries to access the element in the eleventh index of an array that only has a length of ten and a max index of nine. As expected, the exception is thrown and the program stops executing due to the error. Let's change the number in the program to a number that should not trigger the error to check if our exception statement works as intended.

Edit Me on GitHub!

Application Question

Which of the following throws an ArrayIndexOutOfBoundsException?