ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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.

Java Exception Handling Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.