Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Exception
3.
Example
3.1.
Java
4.
Constructors
5.
Public Constructors
5.1.
1. `Throwable()`
5.1.1.
Example
5.2.
2. `Throwable(String message)`
5.2.1.
Example
6.
Protected Constructors
6.1.
1. `Throwable(String message, Throwable cause)`
6.1.1.
Example
6.2.
2. `Throwable(Throwable cause)`
6.2.1.
Example
7.
Methods
7.1.
1. `getMessage()`
7.1.1.
Example
7.2.
2. `getCause()`
7.2.1.
Example
7.3.
3. `printStackTrace()`
7.3.1.
Example
7.4.
4. `toString()`
7.4.1.
Example
8.
Frequently Asked Questions
8.1.
What is the difference between checked and unchecked exceptions in Java?
8.2.
Can we create our own custom exceptions in Java?
8.3.
What is the purpose of the finally block in exception handling?
9.
Conclusion
Last Updated: Aug 14, 2024
Medium

Throwable Class in Java

Introduction 

In Java, the Throwable class is the superclass of all errors & exceptions. It provides a way to handle and manage exceptional conditions that occur during the execution of a program. When an error or exception is thrown, it can be caught and handled using try-catch blocks. This allows developers to easily handle unexpected situations and prevent the program from crashing. 

Throwable Class in Java

In this article, we will talk about the Throwable class, its constructors, methods, and how to use it in Java.

Exception

In Java, an exception is an event that disrupts the normal flow of program execution. It occurs when an error or unexpected condition is encountered. When an exception is thrown, it can be caught and handled using try-catch blocks. This allows the program to continue running without abruptly terminating.

For example 

try {
    int result = 10 / 0; // Division by zero, throws an ArithmeticException
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("An arithmetic exception occurred: " + e.getMessage());
} finally {
    System.out.println("The finally block always executes.");
}


In this code, we have a try block that contains a division by zero operation, which throws an `ArithmeticException`. The catch block is used to handle the exception, where we print an error message. The finally block is optional and always executes, regardless of whether an exception occurred or not.

Example

Suppose we have a program that reads data from a file and performs some operations on it. However, if the file is not found or cannot be read, an exception will be thrown.

  • Java

Java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileReadExample {
public static void main(String[] args) {
try {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
You can also try this code with Online Java Compiler
Run Code


Output

File not found: data.txt (No such file or directory)


In this example, we use a try block to attempt reading from a file named "data.txt". If the file is found, we use a Scanner to read its contents line by line and print them. However, if the file is not found, a `FileNotFoundException` is thrown. We catch this exception in the catch block and print an appropriate error message.

Constructors

The Throwable class provides several constructors that allow you to create instances of Throwable or its subclasses. Here are the commonly used constructors:

1. `Throwable()`: Creates a new Throwable object with no detail message.
 

2. `Throwable(String message)`: Creates a new Throwable object with the specified detail message.
 

3. `Throwable(String message, Throwable cause)`: Creates a new Throwable object with the specified detail message and cause.
 

4. `Throwable(Throwable cause)`: Creates a new Throwable object with the specified cause.


Let’s discuss an example of creating a custom exception class using the Throwable constructors:

public class CustomException extends Exception {
    public CustomException() {
        super();
    }
    
    public CustomException(String message) {
        super(message);
    }
    
    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }
    
    public CustomException(Throwable cause) {
        super(cause);
    }
}


In this code, we define a custom exception class named `CustomException` that extends the `Exception` class. We provide four constructors that match the constructors of the Throwable class. These constructors allow us to create instances of `CustomException` with different combinations of detail messages and causes.

Public Constructors

The Throwable class provides two public constructors that are commonly used:

1. `Throwable()`

This constructor creates a new Throwable object with no detail message. It is used when creating a simple exception without any additional information.

Example

try {
    throw new Throwable();
} catch (Throwable e) {
    System.out.println("A throwable occurred.");
}

2. `Throwable(String message)`

This constructor creates a new Throwable object with the specified detail message. The detail message is a string that describes the exception.

Example

try {
    throw new Throwable("Something went wrong.");
} catch (Throwable e) {
    System.out.println("A throwable occurred: " + e.getMessage());
}


In this example, we throw a Throwable object with a custom detail message. When caught, we print the detail message using the `getMessage()` method.

Note: These public constructors allow you to create instances of Throwable or its subclasses with or without a detail message. They provide flexibility in constructing exceptions based on your specific needs.

Protected Constructors

In addition to the public constructors, the Throwable class also provides protected constructors. These constructors are used when creating custom exception classes that extend Throwable or its subclasses. The protected constructors allow you to set the cause of the exception, which is another Throwable object.

The two commonly used protected constructors are:

1. `Throwable(String message, Throwable cause)`

This constructor creates a new Throwable object with the specified detail message and cause. The cause is the Throwable object that caused the current exception.

Example

public class CustomException extends Exception {
    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }
}
try {
    throw new CustomException("Something went wrong.", new IllegalArgumentException("Invalid argument."));
} catch (CustomException e) {
    System.out.println("Custom exception occurred: " + e.getMessage());
    System.out.println("Cause: " + e.getCause());
}


In this example, we create a custom exception class `CustomException` that extends the `Exception` class. We use the protected constructor to set the detail message and the cause of the exception. When caught, we print the detail message and the cause using the `getMessage()` and `getCause()` methods.

2. `Throwable(Throwable cause)`

This constructor creates a new Throwable object with the specified cause. The detail message is set to `null`.

Example

public class CustomException extends Exception {
    public CustomException(Throwable cause) {
        super(cause);
    }
}
try {
    throw new CustomException(new IllegalArgumentException("Invalid argument."));
} catch (CustomException e) {
    System.out.println("Custom exception occurred.");
    System.out.println("Cause: " + e.getCause());
}


In this example, we create a custom exception class `CustomException` that extends the `Exception` class. We use the protected constructor to set only the cause of the exception. When caught, we print the cause using the `getCause()` method.

Methods

The Throwable class provides several methods that are useful for handling and retrieving information about exceptions. Here are some commonly used methods:

1. `getMessage()`

This method returns the detail message string of the Throwable object. It provides information about the exception that occurred.

Example

try {
    throw new Exception("Something went wrong.");
} catch (Exception e) {
    System.out.println("Exception message: " + e.getMessage());
}

2. `getCause()`

This method returns the cause of the exception as a Throwable object. It allows you to retrieve the underlying exception that caused the current exception.

Example

try {
    // Some code that throws an exception
} catch (Exception e) {
    Throwable cause = e.getCause();
    if (cause != null) {
        System.out.println("Cause: " + cause.toString());
    }
}

3. `printStackTrace()`

This method prints the stack trace of the Throwable object to the standard error stream. It shows the sequence of method invocations that led to the exception.

Example

try {
    // Some code that throws an exception
} catch (Exception e) {
    e.printStackTrace();
}

4. `toString()`

This method returns a string representation of the Throwable object, including the class name and the detail message.

Example

try {
    throw new Exception("Something went wrong.");
} catch (Exception e) {
    System.out.println("Exception: " + e.toString());
}

Frequently Asked Questions

What is the difference between checked and unchecked exceptions in Java?

Checked exceptions are checked at compile-time & must be explicitly handled or declared in the method signature. Unchecked exceptions are not checked at compile-time & can propagate without being caught or declared.

Can we create our own custom exceptions in Java?

Yes, we can create custom exceptions by extending the Exception class or one of its subclasses. This allows us to define specific exception types for our application's needs.

What is the purpose of the finally block in exception handling?

The finally block is used to specify code that should always execute, regardless of whether an exception occurs or not. It is commonly used to release resources, close connections, or perform cleanup tasks.

Conclusion

In this article, we talked about the Throwable class in Java, which serves as the superclass for all errors & exceptions. We learned about the different constructors available in the Throwable class, that includes the  both public and protected constructors, and how they can be used to create instances of Throwable or custom exception classes. We also explained different methods provided by the Throwable class, such as getMessage(), getCause(), printStackTrace(), and toString(), which helps us in handling and retrieving information about exceptions. 


You can also check out our other blogs on Code360.

Live masterclass