What is the importance of the Throwable class and its methods in Java?


The Throwable class is a superclass of all errors and exceptions in Java. Objects that are instances of this class are thrown by the Java Virtual Machine or can be thrown by a throw statement. Similarly, this class or one of its subclasses can be the argument type in a catch clause.

Instances of two subclasses Error and Exception are used to indicate that exceptional situations have occurred, these instances are created in the context of the exceptional situation to include relevant information.

Commonly used exception methods of Throwable class

  • public String getMessage(): returns the message string about the exception.
  • public Throwable getCause(): returns the cause of the exception. It will return null if the cause is unknown or nonexistent.
  • public String toString(): returns a short description of the exception.
  • public void printStackTrace(PrintStream s): prints the short description of the exception (using toString()) + a stack trace for this exception on the error output stream(System.err).

Example

Live Demo

class ArithmaticTest {
   public void division(int num1, int num2) {
      try {
         //java.lang.ArithmeticException here.
         System.out.println(num1/num2);
         //catch ArithmeticException here.
      } catch(ArithmeticException e) {
         //print the message string about the exception.
         System.out.println("getMessage(): " + e.getMessage());
         //print the cause of the exception.
         System.out.println("getCause(): " + e.getCause());
         //print class name + “: “ + message.
         System.out.println("toString(): " + e.toString());
         System.out.println("printStackTrace(): ");
         //prints the short description of the exception + a stack trace for this exception.
         e.printStackTrace();
      }
   }
}
public class Test {
   public static void main(String args[]) {
      //creating ArithmaticTest object
      ArithmaticTest test = new ArithmaticTest();
      //method call
      test.division(20, 0);
   }
}

Output

getMessage(): / by zero
getCause(): null
toString(): java.lang.ArithmeticException: / by zero
printStackTrace():
java.lang.ArithmeticException: / by zero
at ArithmaticTest.division(Test.java:5)
at Test.main(Test.java:27)

raja
raja

e

Updated on: 06-Feb-2020

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements