Get startedGet started for free

Throws

As an exception is thrown, a method can elect to handle the exception with a try-catch or throw the exception to its caller (passing the buck). In this exercise, you will see how to throw an exception rather than handle it with try/catch.

This exercise is part of the course

Data Types and Exceptions in Java

View Course

Exercise instructions

  • Add a try block around the code to getScore(3) and print it.
  • Add a catch block to handle the ArrayIndexOutOfBoundsException caused in the getScore() method.
  • Have getScore(int) throw ArrayIndexOutOfBoundsException instead of try/catching the exception.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

package exceptions;

public class ThrowingExample {

	public static int[] scores = { 75, 97, 83 };

	public static void main(String[] args) {
		// Add a try block
		____ ____
			int lastScore = getScore(3);
			System.out.println("Last score:" + lastScore);
		// Catch the exception thrown by getScore(int)
		____ ____ (____ e) ____
			System.out.println("Tried to access non-existent score");
		}
	}

	// Throw ArrayIndexOutOfBoundsException
	public static int getScore(int index) ____ ____ {
		return scores[index];
	}
}
Edit and Run Code