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
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.