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)
Have Questions? Post them here!
- Create a Zip file using Java Code programmatically
- Eclipse : A java Runtime Environment (JRE) or Java Development kit (JDK) must be available
- How to Sort a LinkedList in Java
- Loading class com.mysql.jdbc.Driver. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver
- How to declare and initialize Array in Java Programming
- [Fix] java: integer number too large compilation error
- Java JDBC Connection with MySQL Driver in VS Code + Troubleshooting
- Reading .xls and .xlsx Excel file using Apache POI Java Library
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- How to get Client IP address using Java Code Example
- Truncate table using Java JDBC Example
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- How to get file path in Idea IntelliJ IDE
- Java Generics explained with simple definition and examples
- Java SE 8 Update 301 available with various bug fixes and security improvements
- Java: Collect Stream as ArrayList or LinkedList
- Java JDBC Connection with PostgreSQL Driver Example
- How to check if Java main thread is alive
- How to fix Java nio NoSuchFileException wile reading a file
- Java 8+ get Day of the Week Examples with LocalDateTime, DateTime, ZonalDateTime and Instant classes
- Ways to Convert Integer or int to Long in Java
- [Java] How to throws Exception using Functional Interface and Lambda code
- [Fix] Spring Boot: mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
- Java: The value of the local variable string is not used
- Java JDBC: Insert Java 8 LocalDate and Time using PreparedStatement
- Indent Python code in Notepad++ - Python
- How to find Sublime Text path of packages installed - Sublime-Text
- Call PHP function on Button click using jquery ajax - PHP
- SharePoint Server 2016 Preview installation error - This Product Key isn't a valid Microsoft Office 2016 Product Key. Check that you've entered it correctly. - SharePoint
- Setting up Java JUnit Project with Eclipse + Maven Example - Java
- [fix] Loading class com.mysql.jdbc.Driver is deprecated - MySQL
- [Solution] Error: brew cask is no longer a brew command - MacOS
- Java Stream flatmap() Examples - Java