Java 7 addSuppression() and getSuppression() Exception Handling


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.

    public final void addSuppressedโ€‹(Throwable exception)

    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;
            }
        }
    
    Exception in thread "main" java.io.IOException: Error occurred while reading data.csv
    	at org.code2care.AddSuppressedExample.someMethod(AddSuppressedExample.java:37)
    	at org.code2care.AddSuppressedExample.main(AddSuppressedExample.java:24)
    	Suppressed: java.io.FileNotFoundException: data.csv (No such file or directory)
    
    		at java.base/java.io.FileInputStream.open0(Native Method)
    		at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
    		at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158)
    		at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
    		at org.code2care.AddSuppressedExample.someMethod(AddSuppressedExample.java:35)
    		... 1 more
    
    	Suppressed: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/prodDb
    		at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:708)
    		at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:230)
    		at org.code2care.AddSuppressedExample.someMethod(AddSuppressedExample.java:42)
    		... 1 more

    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.

    addSuppressed method is thread-safe!



getSuppressed

    public final Throwable[] getSuppressed()

    Returns: an array containing all of the exceptions that were suppressed to deliver this exception.

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


    Example:
     Exception[] suppressedExceptions = primaryException.getSuppressed();
        
        System.out.println("Suppressed exceptions List:");
    
        for (Exception ex : suppressedExceptions) {
            System.out.println(ex);
        }
    Suppressed exceptions:
    java.io.FileNotFoundException: data.csv (No such file or directory)
    java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/prodDb


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:

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

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

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap