What is a Throwable class in Java?

Java 8Object Oriented ProgrammingProgramming

The java.lang.Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.

Following is the declaration for java.lang.Throwable class −

public class Throwable
   extends Object
      implements Serializable

Example

Live Demo

Following example explains the usage of the Throwable class. Here we use the toString() method of the Throwable class to print the exception raised.

import java.lang.*;

public class ThrowableDemo {
   public static void main(String[] args) {
      try {Exception2();
      } 
      catch(Throwable e) {
         System.err.println(e.toString());
      }
   }
   public static void Exception2()throws Throwable {
      throw new Throwable("This is the new Exception");
   }
}

Output

java.lang.Throwable: This is the new Exception
raja
Published on 08-Feb-2018 14:08:58
Advertisements