The toString() method of the java.lang.Throwable class is used to return a string representation of an exception or error. It is commonly used while printing exceptions to understand what went wrong in a program.
Below example demonstrates how Throwable.toString() provides a concise description of an exception.
import java.io.*;
public class GFG {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
Output
java.lang.ArithmeticException: / by zero
Explanation :
- code deliberately causes an ArithmeticException by dividing 10 by 0.
- exception is caught in the catch block.
- e.toString() returns a string containing the exception’s class name and message.
- output shows: java.lang.ArithmeticException: / by zero.
Syntax
public String toString()
- Parameters: This method does not take any parameters.
- Return Value: Returns a String representing the Throwable.
Example: This code demonstrates how to use the toString() method of the Throwable class in Java to get a readable description of an exception.
class GFG {
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
Output
java.lang.NullPointerException
Explanation:
- A NullPointerException is explicitly thrown using throw new NullPointerException().
- The exception is caught in the catch block as a generic Exception.
- e.toString() is called to get a string representation of the exception.
- Since no custom message is provided, it outputs the class name: java.lang.NullPointerExceptio