Java.lang Package Classes

Java Throwable - getMessage() Method



The java.lang.Throwable.getMessage() method returns the detail message string of this throwable.

Syntax

public String getMessage()

Parameters

No parameter is required.

Return Value

Returns the detail message string of this Throwable instance (which may be null).

Exception

NA.

Example:

In the example below, the java.lang.Throwable.getMessage() method is used to get detail message string of the given throwable.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) throws Throwable {
    try{
      int x = 10, y = 0, z;
      z = x/y;
      System.out.println(z);
    }
    catch (Exception e){
      System.out.println("Error occurred due to: " + e.getMessage());
    }
  }
}

The output of the above code will be:

Error occurred due to: / by zero

Example:

Consider one more example to understand the concept better.

import java.lang.*;

public class MyClass {
  public static void main(String[] args){
    try{
      testException();
    }
    catch (Exception e){
      System.out.println("Error: " + e.getMessage());
    }
  }

  //method to throw Exception 
  public static void testException() throws Exception { 
    throw new Exception("New Exception Thrown"); 
  } 
}

The output of the above code will be:

Error: New Exception Thrown

❮ Java.lang - Throwable