Suppressed Exceptions with Example Java

In this article, we will learn about the Suppressed Exceptions with Example Java. Thrown exceptions as the name suggests are exceptions that are thrown in code but somehow ignored. If you remember the execution order of the try-catch-finally block and how it throws values ​​or exceptions, you will remember that the exceptions thrown in the finally the block is thrown even though an exception is thrown in the try block.

Prior to Java 7, logging informs you of these exceptions when they implement, but you have no control over these types of exceptions after the blocking was complete.

Well, with the new features in Java 7, you also have control over these suppressed exceptions.

1. Which exceptions have been removed?

In Java 7, probably the most common use case for the occurrence of suppressed exceptions is a try-with-resources statement. When we encounter an exception in the try block, the application tries to close the resource. If multiple exceptions occur when closing AutoCloseable resources, additional exceptions are added to a primary exception as suppressed exceptions.

To support dropped exceptions, a new constructor and two new methods have been added to the Throwable class (the Exception and Error class) in JDK 7.

Throwable.getSupressed(); // Returns Throwable[]
Throwable.addSupressed(aThrowable);

2. Suppressed exception example

For example, writing to the output stream can throw one exception from the try block and up to two exceptions from the try-with-resources statement when an attempt is made to close the stream.

If an exception is thrown by the try block and one or more exceptions are thrown by the try-with-resources statement, those exceptions are thrown by the try-with-resources statement and the exception thrown by the block is that of the closeStream( ).

You can remove these exceptions by calling the Throwable.getSuppressed() the method from the exception thrown by the try block.

3. Demonstration in different scenarios

For example, I am writing a self-closing resource (i.e. DirtyResource.java) that throws exceptions whether we try to access it or close it. That way, we can spot different behaviors if we access them in other ways.

public class DirtyResource implements AutoCloseable
{
    /**
     * Need to call this method if you want to access this resource
     * @throws RuntimeException no matter how you call this method
     * */
    public void accessResource()
    {
        throw new RuntimeException("I wanted to access this resource. Bad luck. Its dirty resource !!!");
    }
 
    /**
     * The overridden closure method from AutoCloseable interface
     * @throws Exception which is thrown during closure of this dirty resource
     * */
    @Override
    public void close() throws Exception
    {
        throw new NullPointerException("Remember me. I am your worst nightmare !! I am Null pointer exception !!");
    }
}

3.1. Before the suppressed exception function

package com.handyopinion.demo.core;
 
import static java.lang.System.err;
 
public class SuppressedExceptionDemoWithTryFinallyPrevious
{
    /**
    * Executable member function demonstrating suppressed exceptions
    * One exception is lost if not added in suppressed exceptions list
    */
    public static void memberFunction() throws Exception
    {
        DirtyResource resource= new DirtyResource();
        try
        {
              resource.accessResource();
        }
        finally
        {
            resource.close();
        }
    }
 
    public static void main(String[] arguments) throws Exception
   {
      try
      {
          memberFunction();
      }
      catch(Exception ex)
      {
          err.println("Exception encountered: " + ex.toString());
          final Throwable[] suppressedExceptions = ex.getSuppressed();
          final int numSuppressed = suppressedExceptions.length;
          if (numSuppressed > 0)
          {
              err.println("tThere are " + numSuppressed + " suppressed exceptions:");
              for (final Throwable exception : suppressedExceptions)
              {
                  err.println("tt" + exception.toString());
              }
          }
      }
   }
}
 
Output:
 
Exception encountered: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !!

As you can see, only one exception was caught and the second RuntimeException was thrown.

3.2. After removing exception support in Java 7

package com.handyopinion.demo.core;
 
import static java.lang.System.err;
 
public class SuppressedExceptionDemoWithTryFinallyNew
{
    /**
    * Executable member function demonstrating suppressed exceptions
    * Suppressed expression is added back in primary exception
    */
    public static void memberFunction() throws Exception
    {
        Throwable th = null;
        DirtyResource resource= new DirtyResource();
        try
        {
              resource.accessResource();
        }
        catch(Exception e)
        {
            th = e;
        }
        finally
        {
            try
            {
                resource.close();
            }
            catch(Exception e)
            {
                if(th != null)
                {
                    e.addSuppressed(th); //Add to primary exception
                    throw e;
                }
            }
        }
    }
   /**
    * Executable function demonstrating suppressed exceptions.
    */
   public static void main(String[] arguments) throws Exception
   {
      try
      {
          memberFunction();
      }
      catch(Exception ex)
      {
          err.println("Exception encountered: " + ex.toString());
          final Throwable[] suppressedExceptions = ex.getSuppressed();
          final int numSuppressed = suppressedExceptions.length;
          if (numSuppressed > 0)
          {
              err.println("tThere are " + numSuppressed + " suppressed exceptions:");
              for (final Throwable exception : suppressedExceptions)
              {
                  err.println("tt" + exception.toString());
              }
          }
      }
   }
}
 
Output:
 
Exception encountered: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !!
    There are 1 suppressed exceptions:
        java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!!

Here in the catch block, we can access both exceptions. One as the primary exception and the second as the suppressed exception.

3.3. try-with-resource block in a member function and catch the exception

package com.handyopinion.demo.core;
 
import static java.lang.System.err;
 
public class SuppressedExceptionDemoWithTryCatch
{
    public static void memberFunction() throws Exception
    {
        try (DirtyResource resource= new DirtyResource())
          {
              resource.accessResource();
          }
    }
   /**
    * Executable member function demonstrating suppressed exceptions using try-with-resources
    */
   public static void main(String[] arguments) throws Exception
   {
      try
      {
          memberFunction();
      }
      catch(Exception ex)
      {
          err.println("Exception encountered: " + ex.toString());
          final Throwable[] suppressedExceptions = ex.getSuppressed();
          final int numSuppressed = suppressedExceptions.length;
          if (numSuppressed > 0)
          {
              err.println("tThere are " + numSuppressed + " suppressed exceptions:");
              for (final Throwable exception : suppressedExceptions)
              {
                  err.println("tt" + exception.toString());
              }
          }
      }
   }
}
 
Output:
 
Exception encountered: java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!!
    There are 1 suppressed exceptions:
        java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !!

Large !! We can see the two exceptions when we use try-with-resources in the member function.

3.4. Standard block of attempts with resources

package com.handyopinion.demo.core;
 
public class SuppressedExceptionDemoWithTryWithResource
{
   /**
    * Demonstrating suppressed exceptions using try-with-resources
    */
   public static void main(String[] arguments) throws Exception
   {
      try (DirtyResource resource= new DirtyResource())
      {
          resource.accessResource();
      }
   }
}
 
Output:
 
Exception in thread "main" java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!!
    at DirtyResource.accessResource(DirtyResource.java:9)
    at SuppressedExceptionDemoWithTryWithResource.main(SuppressedExceptionDemoWithTryWithResource.java:12)
    Suppressed: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !!
        at DirtyResource.close(DirtyResource.java:19)
        at SuppressedExceptionDemoWithTryWithResource.main(SuppressedExceptionDemoWithTryWithResource.java:13)

Well, it’s really great to see the full output of the information, even with the exceptions removed.

Next Articles

1. Java 8 Features 
2. Java 8 Functional Interfaces

Please share this post:
Posts created 58

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: