Saturday, September 6, 2025
HomeLanguagesJavaThrowable getMessage() method in Java with Examples

Throwable getMessage() method in Java with Examples

The getMessage() method of Throwable class is used to return a detailed message of the Throwable object which can also be null. One can use this method to get the detail message of exception as a string value.

Syntax:

public String getMessage()

Return Value: This method returns the detailed message of this Throwable instance.

Below programs demonstrate the getMessage() method of java.lang.Throwable Class

Example 1:




// Java program to demonstrate
// the getMessage() Method.
  
import java.io.*;
  
class GFG {
  
    // Main Method
    public static void main(String[] args)
        throws Exception
    {
  
        try {
  
            // divide the numbers
            divide(2, 0);
        }
  
        catch (ArithmeticException e) {
  
            System.out.println("Message String = "
                               + e.getMessage());
        }
    }
  
    // method which divide two numbers
    public static void divide(int a, int b)
        throws ArithmeticException
    {
  
        int c = a / b;
  
        System.out.println("Result:" + c);
    }
}


Output:

Message String = / by zero

Example 2:




// Java program to demonstrate
// the getMessage() Method.
  
import java.io.*;
  
class GFG {
  
    // Main Method
    public static void main(String[] args)
        throws Exception
    {
  
        try {
  
            test();
        }
  
        catch (Throwable e) {
  
            System.out.println("Message of Exception : "
                               + e.getMessage());
        }
    }
  
    // method which throws UnsupportedOperationException
    public static void test()
        throws UnsupportedOperationException
    {
  
        throw new UnsupportedOperationException();
    }
}


Output:

Message of Exception : null

References:
https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getMessage()

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11868 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS