The toString() method of Java.lang.Throwable class used to return a String representation of this Throwable which consists of the name of the class of this object, a colon and a space(“: “) and a string which is same as result of invoking this object’s getLocalizedMessage() method and If getLocalizedMessage returns null, then just the class name is returned.
Syntax:
public String toString()
Return Value: This method returns String representation of this Throwable if a Exception occurs.
Below programs illustrate the toString() method of Throwable class:
Example 1:
import java.io.*;
class GFG {
public static void main(String[] args)
throws Exception
{
try {
testException();
}
catch (Throwable e) {
System.out.println( "Exception: "
+ e.toString());
}
}
public static void testException()
throws Exception
{
throw new Exception( "New Exception Thrown" );
}
}
|
Output:
Exception: java.lang.Exception: New Exception Thrown
Example 2:
import java.io.*;
class GFG {
public static void main(String[] args)
throws Exception
{
try {
int a = 4 , b = 0 ;
int c = a / b;
}
catch (Throwable e) {
System.out.println( "Exception: "
+ e.toString());
}
}
}
|
Output:
Exception: java.lang.ArithmeticException: / by zero
References:
https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#toString()