![]() |
VOOZH | about |
The addSuppressed?(Throwable exception) method of a Throwable class used to append the exception to the exceptions that were suppressed in order to deliver this exception. This method is a thread-safe method. This method is typically called by try-catch clause. The suppression behavior of a Throwable is enabled unless disabled via a constructor and When suppression is disabled, this method does nothing other than to validate its argument.
In default behavior of try-finally block, where we have two exceptions, the original exception is suppressed and exception from finally block is shown. In some situation, finally block is used in order to close the resource and in that situation we want to see the original exception, with some exceptions from the final block, that closed our resource and failed so we can add those exceptions which were suppressed via this method.
If there are multiple sibling exceptions and only one can be propagated, then this method can be used to propagate that method.
Syntax:
public final void addSuppressed?(Throwable exception)
Parameters: This method accepts only one parameter exception which we want to add as a suppressed exception.
Returns: This method does not returns anything.
Exceptions: This method throws following exceptions:
Below programs illustrate the addSuppressed?() method:
Example 1:
Suppressed Exceptions: java.lang.ArithmeticException
Example 2:
Suppressed Exceptions: java.lang.ArithmeticException java.lang.IndexOutOfBoundsException java.lang.ClassNotFoundException java.io.IOException
Example 3: To show IllegalArgumentException
Exception:java.lang.IllegalArgumentException: Self-suppression not permitted
Example 4: To show NullPointerException
Exception:java.lang.NullPointerException: Cannot suppress a null exception.
References:
https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#addSuppressed(java.lang.Throwable)