addSuppression() and getSuppression() are the two new methods that were introduced in Java 7 as a part of the java.lang.Throwable the parent class for exception handing.
addSuppressed
You can use the addSuppressed method in situations where there are multiple exceptions that are occurring during the execution of a single try block, and you want to associate all the exceptions with a primary exception that caused the block to fail.
Parameters: exception - the exception to be added to the list of suppressed exceptions
Throws:
IllegalArgumentException - if exception is this throwable; a throwable cannot suppress itself.
NullPointerException - if exception is null
Example:
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class AddSuppressedExample {
public static void main(String[] args) throws IOException {
AddSuppressedExample addSuppressedExample = new AddSuppressedExample();
addSuppressedExample.someMethod();
}
public void someMethod() throws IOException {
IOException primaryException = null;
try {
FileInputStream fileInputStream = new FileInputStream("data.csv");
} catch (IOException exception) {
primaryException = new IOException("Error occurred while reading data.csv");
primaryException.addSuppressed(exception);
}
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/prodDb", "prod", "123456");
throw new IOException("IOException occurred while connecting to Database!");
} catch (IOException exception) {
if (primaryException == null) {
primaryException = new IOException("An error occurred while establishing database connection");
}
primaryException.addSuppressed(exception);
} catch (SQLException exception) {
if (primaryException == null) {
primaryException = new IOException("An error occurred while executing database query");
}
primaryException.addSuppressed(exception);
}
if (primaryException != null) {
throw primaryException;
}
}
As you can see in the above example, we have a method someMethod() that can throw an IOException. The method has two try blocks that can throw exceptions - one that can throw IOException and the other that can throw SQLException.
With the help of addSuppressed() we are able to handle both exceptions and throw a single primary exception that represents the main error.
getSuppressed
- getSuppressed method returns an array of all suppressed exceptions.
- If no exceptions were suppressed or suppression is disabled, an empty array is returned.
- getSupressed method is thread-safe, so it can be called from multiple threads concurrently without causing any issues.
Returns: an array containing all of the exceptions that were suppressed to deliver this exception.
Example:
Exception[] suppressedExceptions = primaryException.getSuppressed();
System.out.println("Suppressed exceptions List:");
for (Exception ex : suppressedExceptions) {
System.out.println(ex);
}
Summary:
In situations where multiple exceptions can occur in a single try block, it can be challenging to handle and track all the exceptions. In such cases, the addSuppressed() method allows you to associate all the exceptions with a primary exception that caused the block to fail. Thus helping to capture and communicate all the exceptions that occurred in a single catch block.
getSuppressed() method complements the addSuppressed() method by providing a way to retrieve all suppressed exceptions that are associated with a primary exception. You can use this method for logging, debugging, or providing more detailed error messages to users.
Reference:
- Throwable getSuppressed(): https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/Throwable.html#getSuppressed()
- Throwable addSuppressed(): https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/Throwable.html#addSuppressed(java.lang.Throwable)
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- macOS Sonoma - Cant install the software because it is not currently available from the Software Update Server - MacOS
- Get Absolute Relative Path of File in IDEA IntelliJ - Java
- Static IP MTNL available at Rs. 200 per month - HowTos
- Java Decompiler Eclipse Plugin - Eclipse
- Cmd command get current directory location - Windows
- How to check of Updates on Microsoft Edge Browser on Mac (macOS) - MacOS
- [fix] zsh: command not found: telnet on Mac - MacOS
- 9 Border to DIV Element in HTML Examples - Html