Throwable in Java | Throwable Class, Example
We know all exceptions and errors in Java are represented by classes. All these classes are organized as subclasses in a hierarchy under a superclass called Throwable.
Throwable in Java is a predefined class that is the superclass of all kinds of exceptions and errors which may occur in Java program. This class is present in java.lang package.
Throwable class extends Object class, which is at the root of the class hierarchy. Therefore, throwable class is itself a subclass of the superclass of all Java classes, Object class.
JVM throws only those exception objects, which are instances of Throwable class or one of its subclasses. In other words, when an exceptional situation occurs in a Java program, JVM generates an exception object to represent that situation. And this exception object is of a type derived from the Throwable class.
The same is true for Java throw statement. Only Throwable class or one of its subclasses can be argument type in the catch clause. In other words, when we handle an exception using try-catch blocks, the catch block can catch and handle the exception that is an instance of Throwable class itself or any of its derived subclasses.
For example, we can write a catch block as:
try {
// Code that may throw exceptions
} catch (Throwable t) {
// Handling code for exceptions of type Throwable or its subclasses
}
In this catch block, the argument t can catch exceptions of any type derived from Throwable. This allows us to catch and handle various types of exceptions systematically, making our code more robust and adaptable to different exceptional scenarios.
A Throwable object contains a snapshot of the execution stack of its thread at a time of its creation. This stack trace tells the sequence of method calls that led to the exceptional condition. In addition, it also contains a descriptive message in the string form, which gives more information about error or exception as well as its root cause.
Throwable Class Hierarchy in Java
Throwable class is the top most class in the exception class hierarchy but it is also an immediate subclass of Object class that is located at the root of exception hierarchy. The hierarchy of this class has shown in the below diagram.
From the above figure, Throwable class which is derived from the Object class is the top of exception hierarchy from which all kinds of error and exception classes are derived.
Throwable class is the superclass of exception class in Java. Other than the exception class, the error class is also a subclass of Throwable class. Using Throwable class, you can also create your own custom or user-defined exception.
Constructors of Throwable Class
The Throwable class provides four kinds of constructors that are as:
(1) public Throwable(): This is a default constructor that creates a Throwable object with a null information. Here, null information means when we use the default constructor to create Throwable object, it initializes the object without providing any specific error or exception message about the error or exception that occurred.
(2) public Throwable(String msg): This form of constructor constructs a Throwable object with a detail message specified by the programmer.
(3) public Throwable(String msg, Throwable cause): This form of constructor constructs a Throwable object with a specified message by the programmer and the cause behind the exception.
(4) public Throwable(Throwable cause): This form of constructor constructs a new Throwable object with the cause behined the exception.
Methods of Throwable Class in Java
All exception classes, including user-defined class, use all the methods provided by Throwable class. Exception class does not define its own any methods. Java provides the following non-static methods in the Throwable class through which we can use to retrieve and know details of an exception.
An important list of methods present in Throwable class is as follows:
1. getMessage(): The getMessage() method returns a detail message of exception that has occurred. The general syntax for getMessage() is as follows:
public String getMessage()
We initialize the detail message in the Throwable constructor that can be displayed using the following statement:
System.out.println(e.getMessage());
Since getMessage() method returns a string, we can store string message returned by getMessage() method in a string variable and the content of string variable can be displayed using the following statement like this:
String str = e.getMessage();
System.out.println(str);
2. toString(): The toString() method returns a short information about an exception in the form of string. The Throwable class overrides toString() method of Object class. We can display the information on the screen using the println() method. The following syntax can be used:
public String toString()
For example:
System.out.println(e.toString());
Or,
// In the below statement, str is a reference variable.
// This variable stores information about an exception returned by toString() method in the form string.
String str = e.toString();
System.out.println(str);
3. printStackTrace(): This method prints the stack trace of an exception. It gives information about the name of exception, reason behind the exception, the line at which the exception occurs in the case of nested method calls. The general syntax for printStackTrace() method is as follows:
public void printStackTrace() // It does not return anything.
For example:
e.printStackTrace(); // e is an exception type variable.
4. fillInStackTrace(): This method returns a Throwable object that contains a completed stack trace. The object can be rethrown. The basic syntax for fillInStackTrace() method is as below:
public Throwable fillInStackTrace()
5. getStackTrace(): The getStackTrace() method returns an array that contains each element on the stack trace. The element at index 0 represents the top of call stack and the last element represents the bottom of call stack. The general syntax for this method is as follows:
public StackTraceElement[] getStackTrace()
6. getCause(): The getCause() method returns the exception that caused the occurrence of the current exception. If there is no caused exception, then the null is returned. The general syntax for this method is as follows:
public Throwable getCause()
7. initCause(): The initCause() method joins “causeExc” with the invoking exception and returns a reference to the exception. The general syntax for using this method is as below:
public Throwable initCause(Throwable causeExc)
Example Programs based on Throwable Methods
Let’s take some important example programs based on the methods of Throwable class.
Example 1:
public class ThrowableMessageExample
{
public static int divide(int x, int y) throws Throwable {
if (y == 0) {
// Create a Throwable object with a custom message
Throwable error = new Throwable("Division by zero is not allowed");
throw error;
}
return x / y;
}
public static void main(String[] args)
{
try {
// Simulate an error condition
int result = divide(10, 0);
} catch (Throwable t) {
// Catch the Throwable object and retrieve the error message
String errorMessage = t.getMessage();
if (errorMessage != null) {
System.out.println("Caught an exception: " + errorMessage);
} else {
System.out.println("Caught an exception with no specific message.");
}
}
}
}
Output: Caught an exception: Division by zero is not allowed
In this example code, we have used the getMessage() method of Throwable class to retrieve the error message associated with the Throwable object. If the errorMessage is not null, we print it as part of the “Caught an exception” message. If the errorMessage is null, it will print “Caught an exception with no specific message”.
Example 2:
public class PrintStackTraceExample {
public static void main(String[] args)
{
try {
// Simulate an error condition
int result = 10 / 0; // This will cause an ArithmeticException
} catch (Throwable t) {
// Catch the Throwable object and print the stack trace
t.printStackTrace();
}
}
}
Output: java.lang.ArithmeticException: / by zero at PrintStackTraceExample.main(PrintStackTraceExample.java:6)
In this example code, we intentionally create an ArithmeticException object by attempting to divide by zero. When the exception occurs, we catch it using a catch block and then use the printStackTrace() method to print the exception’s stack trace.
The stack trace shows the type of exception (java.lang.ArithmeticException), a brief description (“/ by zero”), and the location where the exception occurred (in the main method at line 6 of the PrintStackTraceExample.java file).
Example 3:
public class ThrowableExample {
public static void main(String[] args)
{
try {
int result = divide(10, 0);
} catch (Throwable initialException) {
// Create a Throwable object and set the initial exception as its cause
Throwable th = new Throwable("An error occurred");
th.initCause(initialException);
// Print the new exception.
System.out.println("New Exception: " + th.getMessage());
// Retrieve and print the cause behind the exception.
Throwable cause = th.getCause();
if (cause != null) {
System.out.println("Cause: " + cause.getMessage());
}
}
}
public static int divide(int x, int y) throws Throwable {
if (y == 0) {
// Create an ArithmeticException object.
Throwable th = new ArithmeticException("Division by zero is not allowed");
throw th;
}
return x / y;
}
}
Output: New Exception: An error occurred Cause: Division by zero is not allowed
Java language provides a hierarchy of classes that represent different types of exceptions. These classes are derived from java.lang.Throwable class. In Java, Throwable class defines several useful methods that can be used for getting and knowing the details of an exception. Hope that this tutorial has explained almost all important points related to Throwable class. In the next, we will understand different types of errors in Java with examples.
Thanks for reading!!!