Throwable toString() method in Java with Examples
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:
// Java program to demonstrate // the toString() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException(); } catch (Throwable e) { // print using tostring() System.out.println("Exception: " + e.toString()); } } // method which throws Exception public static void testException() throws Exception { throw new Exception("New Exception Thrown"); } } |
Exception: java.lang.Exception: New Exception Thrown
Example 2:
// Java program to demonstrate // the toString() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // divide two numbers int a = 4, b = 0; int c = a / b; } catch (Throwable e) { // print using tostring() System.out.println("Exception: " + e.toString()); } } } |
Exception: java.lang.ArithmeticException: / by zero
References:
https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#toString()
Recommended Posts:
- Throwable printStackTrace() method in Java with Examples
- Throwable getStackTrace() method in Java with Examples
- Throwable initCause() method in Java with Examples
- Throwable getCause() method in Java with Examples
- Throwable getSuppressed() method in Java with Examples
- Throwable addSuppressed() method in Java with Examples
- Throwable getLocalizedMessage() method in Java with Examples
- Throwable setStackTrace() method in Java with Examples
- Throwable getMessage() method in Java with Examples
- AtomicInteger toString() method in Java with examples
- BigDecimal toString() Method in Java with Examples
- Path toString() method in Java with Examples
- StringBuffer toString() method in Java with Examples
- Year toString() method in Java with Examples
- Pattern toString() Method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



