Home »
Java »
Java Programs
Java program to get exception message using getMessage() method
Java example to get exception message using getMessage() method.
Submitted by Nidhi, on April 20, 2022
Problem statement
In this program, we will use the getMessage() method to get an exception message in the catch block and print it.
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.
Java Exception Handling Programs »