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!
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
- How to Toggle Light/Dark Mode in Google Colab - Google
- [Solved] Notepad++ Menu Bar Missing - NotepadPlusPlus
- SharePoint - The URL is invalid. It may refer to a nonexistent file or folder, or refer to a valid file or folder that is not in the current Web. - SharePoint
- Can we move apps like WhatsApp, Facebook to external MicroSD card - WhatsApp
- MacBook - Time Limit - You have reached your time limit, Ignore Limit - MacOS
- Here are the steps to Install Python on macOS Sequoia 15.0 - Python
- [Fix] Cannot connect to Microsoft SQL Server, Error: 18456 - Microsoft
- Create SharePoint Site Collection using PowerShell New-SPSite - SharePoint