Q:

Java program to get exception message using getMessage() method

belongs to collection: Java Exception Handling Programs

0

Java program to get exception message using getMessage() method

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will use the getMessage() method to get an exception message in the catch block and print it.

Program/Source Code:

The source code to get the exception message using the getMessage() method is given below. The given program is compiled and executed successfully.

// Java program to get exception message using 
// getMessage() method

public class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[10];
      array[10] = 10;
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Exception: " + e.getMessage());
    }
    System.out.println("Program finished");
  }
}

Output:

Exception: Index 10 out of bounds for length 10
Program finished

Explanation:

In the above program, we created a class Main. The Main class contains the main() method.

The main() method is the entry point for the program. And, we generated ArrayOutOfBoundException in the try block and catch it in the catch exception. Then we get the exception message using the getMessage() method and printed the message.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to create a custom exception class... >>
<< Java program to implement nested try catch block...