Java.lang Package Classes

Java Throwable - toString() Method



The java.lang.Throwable.toString() method returns a short description of this throwable. The result is the concatenation of:

  • the name of the class of this object
  • ": " (a colon and a space)
  • the result of invoking this object's getLocalizedMessage() method

If getLocalizedMessage returns null, then just the class name is returned.

Syntax

public String toString()

Parameters

No parameter is required.

Return Value

Returns a string representation of this throwable.

Exception

NA.

Example:

In the example below, the java.lang.Throwable.toString() method is used to get the short description 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 - " + e.toString());
    }
  }
}

The output of the above code will be:

Error - java.lang.ArithmeticException: / 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.toString());
    }
  }

  //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 - java.lang.Exception: New Exception Thrown

❮ Java.lang - Throwable