The getMessage() method of the Throwable class is used to retrieve the detailed message associated with an exception or error. It returns the message passed when the exception object was created. If no message is provided, the method returns null.
- Returns the detailed exception message as a String.
- Helps identify the cause of an exception.
- Returns null if no message was specified.
Example: Retrieving a Custom Exception Message
class Main {
public static void main(String[] args) {
try {
throw new Exception("Invalid user input");
}
catch (Exception e) {
System.out.println("Error Message: " + e.getMessage());
}
}
}
Output
Error Message: Invalid user input
Explanation: In this example, an Exception is thrown with the message "Invalid user input". The exception is caught in the catch block, and the getMessage() method returns the same message, which is then displayed on the console. This method is useful for showing meaningful error information during exception handling.
Syntax
public String getMessage()
Returns
- A String containing the exception message.
- null if no message is associated with the exception.
Example: ArithmeticException
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);
}
}
Explanation: In this example, the divide() method attempts to divide a number by zero, which throws an ArithmeticException. The exception is caught in the catch block, and the getMessage() method returns the error message "/ by zero", which is displayed on the console.
Example: Exception Without a Message
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();
}
}
Explanation: In this example, the test() method throws an UnsupportedOperationException without providing any message. Since no message is associated with the exception, calling getMessage() returns null, which is printed as the output.
Advantages of getMessage() Method
- Provides Clear Error Details: Returns a descriptive message about the exception.
- Simplifies Debugging: Helps identify the cause of errors quickly.
- Improves Error Handling: Enables meaningful messages to be displayed to users or developers.
- Easy to Use: Can be called directly inside a
catchblock. - Supports Custom Exceptions: Returns custom messages defined while creating exceptions.