1 /*
2 * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
152 * @since JDK1.0
153 */
154 public class Throwable implements Serializable {
155 /** use serialVersionUID from JDK 1.0.2 for interoperability */
156 private static final long serialVersionUID = -3042686055658047285L;
157
158 /**
159 * Native code saves some indication of the stack backtrace in this slot.
160 */
161 private transient Object backtrace;
162
163 /**
164 * Specific details about the Throwable. For example, for
165 * {@code FileNotFoundException}, this contains the name of
166 * the file that could not be found.
167 *
168 * @serial
169 */
170 private String detailMessage;
171
172 /**
173 * The throwable that caused this throwable to get thrown, or null if this
174 * throwable was not caused by another throwable, or if the causative
175 * throwable is unknown. If this field is equal to this throwable itself,
176 * it indicates that the cause of this throwable has not yet been
177 * initialized.
178 *
179 * @serial
180 * @since 1.4
181 */
182 private Throwable cause = this;
183
184 /**
185 * The stack trace, as returned by {@link #getStackTrace()}.
186 *
187 * @serial
188 * @since 1.4
189 */
190 private StackTraceElement[] stackTrace;
191 /*
192 * This field is lazily initialized on first use or serialization and
193 * nulled out when fillInStackTrace is called.
194 */
195
196 /**
197 * The list of suppressed exceptions, as returned by
198 * {@link #getSuppressedExceptions()}.
199 *
200 * @serial
201 * @since 1.7
202 */
203 private List<Throwable> suppressedExceptions = null;
204 /*
205 * This field is lazily initialized when the first suppressed
206 * exception is added.
207 *
208 * OutOfMemoryError is preallocated in the VM for better OOM
209 * diagnosability during VM initialization. Constructor can't
210 * be not invoked. If a new field to be added in the future must
211 * be initialized to non-null, it requires a synchronized VM change.
212 */
213
214 /** Message for trying to suppress a null exception. */
215 private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
216
217 /** Caption for labeling causative exception stack traces */
218 private static final String CAUSE_CAPTION = "Caused by: ";
219
220 /** Caption for labeling suppressed exception stack traces */
221 private static final String SUPPRESSED_CAPTION = "Suppressed: ";
222
223 /**
224 * Constructs a new throwable with {@code null} as its detail message.
225 * The cause is not initialized, and may subsequently be initialized by a
226 * call to {@link #initCause}.
227 *
228 * <p>The {@link #fillInStackTrace()} method is called to initialize
229 * the stack trace data in the newly created throwable.
230 */
231 public Throwable() {
232 fillInStackTrace();
233 }
234
235 /**
236 * Constructs a new throwable with the specified detail message. The
555 */
556 public void printStackTrace(PrintStream s) {
557 printStackTrace(new WrappedPrintStream(s));
558 }
559
560 private void printStackTrace(PrintStreamOrWriter s) {
561 // Guard against malicious overrides of Throwable.equals by
562 // using a Set with identity equality semantics.
563 Set<Throwable> dejaVu =
564 Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
565 dejaVu.add(this);
566
567 synchronized (s.lock()) {
568 // Print our stack trace
569 s.println(this);
570 StackTraceElement[] trace = getOurStackTrace();
571 for (StackTraceElement traceElement : trace)
572 s.println("\tat " + traceElement);
573
574 // Print suppressed exceptions, if any
575 for (Throwable se : getSuppressedExceptions())
576 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
577
578 // Print cause, if any
579 Throwable ourCause = getCause();
580 if (ourCause != null)
581 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
582 }
583 }
584
585 /**
586 * Print our stack trace as an enclosed exception for the specified
587 * stack trace.
588 */
589 private void printEnclosedStackTrace(PrintStreamOrWriter s,
590 StackTraceElement[] enclosingTrace,
591 String caption,
592 String prefix,
593 Set<Throwable> dejaVu) {
594 assert Thread.holdsLock(s.lock());
595 if (dejaVu.contains(this)) {
596 s.println("\t[CIRCULAR REFERENCE:" + this + "]");
597 } else {
598 dejaVu.add(this);
599 // Compute number of frames in common between this and enclosing trace
600 StackTraceElement[] trace = getOurStackTrace();
601 int m = trace.length - 1;
602 int n = enclosingTrace.length - 1;
603 while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
604 m--; n--;
605 }
606 int framesInCommon = trace.length - 1 - m;
607
608 // Print our stack trace
609 s.println(prefix + caption + this);
610 for (int i = 0; i <= m; i++)
611 s.println(prefix + "\tat " + trace[i]);
612 if (framesInCommon != 0)
613 s.println(prefix + "\t... " + framesInCommon + " more");
614
615 // Print suppressed exceptions, if any
616 for (Throwable se : getSuppressedExceptions())
617 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
618 prefix +"\t", dejaVu);
619
620 // Print cause, if any
621 Throwable ourCause = getCause();
622 if (ourCause != null)
623 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
624 }
625 }
626
627 /**
628 * Prints this throwable and its backtrace to the specified
629 * print writer.
630 *
631 * @param s {@code PrintWriter} to use for output
632 * @since JDK1.1
633 */
634 public void printStackTrace(PrintWriter s) {
635 printStackTrace(new WrappedPrintWriter(s));
636 }
707 * method. Generally speaking, the array returned by this method will
708 * contain one element for every frame that would be printed by
709 * {@code printStackTrace}.
710 *
711 * @return an array of stack trace elements representing the stack trace
712 * pertaining to this throwable.
713 * @since 1.4
714 */
715 public StackTraceElement[] getStackTrace() {
716 return getOurStackTrace().clone();
717 }
718
719 private synchronized StackTraceElement[] getOurStackTrace() {
720 // Initialize stack trace if this is the first call to this method
721 if (stackTrace == null) {
722 int depth = getStackTraceDepth();
723 stackTrace = new StackTraceElement[depth];
724 for (int i=0; i < depth; i++)
725 stackTrace[i] = getStackTraceElement(i);
726 }
727 return stackTrace;
728 }
729
730 /**
731 * Sets the stack trace elements that will be returned by
732 * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
733 * and related methods.
734 *
735 * This method, which is designed for use by RPC frameworks and other
736 * advanced systems, allows the client to override the default
737 * stack trace that is either generated by {@link #fillInStackTrace()}
738 * when a throwable is constructed or deserialized when a throwable is
739 * read from a serialization stream.
740 *
741 * @param stackTrace the stack trace elements to be associated with
742 * this {@code Throwable}. The specified array is copied by this
743 * call; changes in the specified array after the method invocation
744 * returns will have no affect on this {@code Throwable}'s stack
745 * trace.
746 *
747 * @throws NullPointerException if {@code stackTrace} is
748 * {@code null}, or if any of the elements of
749 * {@code stackTrace} are {@code null}
750 *
751 * @since 1.4
752 */
753 public void setStackTrace(StackTraceElement[] stackTrace) {
754 StackTraceElement[] defensiveCopy = stackTrace.clone();
755 for (int i = 0; i < defensiveCopy.length; i++)
756 if (defensiveCopy[i] == null)
757 throw new NullPointerException("stackTrace[" + i + "]");
758
759 synchronized (this) {
760 this.stackTrace = defensiveCopy;
761 }
762 }
763
764 /**
765 * Returns the number of elements in the stack trace (or 0 if the stack
766 * trace is unavailable).
767 *
768 * package-protection for use by SharedSecrets.
769 */
770 native int getStackTraceDepth();
771
772 /**
773 * Returns the specified element of the stack trace.
774 *
775 * package-protection for use by SharedSecrets.
776 *
777 * @param index index of the element to return.
778 * @throws IndexOutOfBoundsException if {@code index < 0 ||
779 * index >= getStackTraceDepth() }
780 */
781 native StackTraceElement getStackTraceElement(int index);
782
783 private void readObject(ObjectInputStream s)
784 throws IOException, ClassNotFoundException {
785 s.defaultReadObject(); // read in all fields
786 List<Throwable> suppressed = null;
787 if (suppressedExceptions != null &&
788 !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
789 suppressed = new ArrayList<Throwable>();
790 for (Throwable t : suppressedExceptions) {
791 if (t == null)
792 throw new NullPointerException(NULL_CAUSE_MESSAGE);
793 suppressed.add(t);
794 }
795 }
796 suppressedExceptions = suppressed;
797 }
798
799 private synchronized void writeObject(ObjectOutputStream s)
800 throws IOException
801 {
802 getOurStackTrace(); // Ensure that stackTrace field is initialized.
803 s.defaultWriteObject();
804 }
805
806 /**
807 * Adds the specified exception to the list of exceptions that
808 * were suppressed, typically by the {@code try}-with-resources
809 * statement, in order to deliver this exception.
810 *
811 * <p>Note that when one exception {@linkplain
812 * #initCause(Throwable) causes} another exception, the first
813 * exception is usually caught and then the second exception is
814 * thrown in response. In contrast, when one exception suppresses
815 * another, two exceptions are thrown in sibling code blocks, such
816 * as in a {@code try} block and in its {@code finally} block, and
817 * control flow can only continue with one exception so the second
818 * is recorded as a suppressed exception of the first.
819 *
820 * @param exception the exception to be added to the list of
821 * suppressed exceptions
822 * @throws NullPointerException if {@code exception} is null
823 * @throws IllegalArgumentException if {@code exception} is this
824 * throwable; a throwable cannot suppress itself.
825 * @since 1.7
826 */
827 public synchronized void addSuppressedException(Throwable exception) {
828 if (exception == null)
829 throw new NullPointerException(NULL_CAUSE_MESSAGE);
830 if (exception == this)
831 throw new IllegalArgumentException("Self-suppression not permitted");
832
833 if (suppressedExceptions == null)
834 suppressedExceptions = new ArrayList<Throwable>();
835 suppressedExceptions.add(exception);
836 }
837
838 private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
839
840 /**
841 * Returns an array containing all of the exceptions that were
842 * suppressed, typically by the {@code try}-with-resources
843 * statement, in order to deliver this exception.
844 *
845 * @return an array containing all of the exceptions that were
846 * suppressed to deliver this exception.
847 * @since 1.7
848 */
849 public synchronized Throwable[] getSuppressedExceptions() {
850 if (suppressedExceptions == null)
851 return EMPTY_THROWABLE_ARRAY;
852 else
853 return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
854 }
855 }
|
1 /*
2 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
152 * @since JDK1.0
153 */
154 public class Throwable implements Serializable {
155 /** use serialVersionUID from JDK 1.0.2 for interoperability */
156 private static final long serialVersionUID = -3042686055658047285L;
157
158 /**
159 * Native code saves some indication of the stack backtrace in this slot.
160 */
161 private transient Object backtrace;
162
163 /**
164 * Specific details about the Throwable. For example, for
165 * {@code FileNotFoundException}, this contains the name of
166 * the file that could not be found.
167 *
168 * @serial
169 */
170 private String detailMessage;
171
172 /*
173 * To allow Throwable objects to be made immutable and safely
174 * reused by the JVM, such as pre-allocated OutOfMemoryErrors, the
175 * fields of Throwable that are writable in response to user
176 * actions, cause and suppressedExceptions, obey the following
177 * protocol:
178 *
179 * 1) The fields are initialized to a non-null sentinel value
180 * which indicates the value has logically not been set.
181 *
182 * 2) Writing a null to the field indicates further writes
183 * are forbidden
184 *
185 * 3) The sentinel value may be replaced with another non-null
186 * value.
187 *
188 * Implementations of the HotSpot JVM have preallocated
189 * OutOfMemoryError objects to provide for better diagnosability
190 * of that situation. These objects are created without calling
191 * the constructor for that class and the fields in question are
192 * initialized to null. To support this capability, any new
193 * fields added to Throwable that require being initialized to a
194 * non-null value require a coordinated JVM change.
195 */
196
197 /**
198 * The throwable that caused this throwable to get thrown, or null if this
199 * throwable was not caused by another throwable, or if the causative
200 * throwable is unknown. If this field is equal to this throwable itself,
201 * it indicates that the cause of this throwable has not yet been
202 * initialized.
203 *
204 * @serial
205 * @since 1.4
206 */
207 private Throwable cause = this;
208
209 /**
210 * The stack trace, as returned by {@link #getStackTrace()}.
211 *
212 * @serial
213 * @since 1.4
214 */
215 private StackTraceElement[] stackTrace;
216
217 // Setting this static field introduces an acceptable
218 // initialization dependency on a few java.util classes.
219 private static final List<Throwable> suppressedSentinel =
220 Collections.unmodifiableList(new ArrayList<Throwable>(0));
221
222 /**
223 * The list of suppressed exceptions, as returned by {@link
224 * #getSuppressed()}. The list is initialized to a zero-element
225 * unmodifiable sentinel list. When a serialized Throwable is
226 * read in, if the {@code suppressedExceptions} field points to a
227 * zero-element list, the field is reset to the sentinel value.
228 *
229 * @serial
230 * @since 1.7
231 */
232 private List<Throwable> suppressedExceptions = suppressedSentinel;
233
234 /** Message for trying to suppress a null exception. */
235 private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
236
237 /** Message for trying to suppress oneself. */
238 private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
239
240 /** Caption for labeling causative exception stack traces */
241 private static final String CAUSE_CAPTION = "Caused by: ";
242
243 /** Caption for labeling suppressed exception stack traces */
244 private static final String SUPPRESSED_CAPTION = "Suppressed: ";
245
246 /**
247 * Constructs a new throwable with {@code null} as its detail message.
248 * The cause is not initialized, and may subsequently be initialized by a
249 * call to {@link #initCause}.
250 *
251 * <p>The {@link #fillInStackTrace()} method is called to initialize
252 * the stack trace data in the newly created throwable.
253 */
254 public Throwable() {
255 fillInStackTrace();
256 }
257
258 /**
259 * Constructs a new throwable with the specified detail message. The
578 */
579 public void printStackTrace(PrintStream s) {
580 printStackTrace(new WrappedPrintStream(s));
581 }
582
583 private void printStackTrace(PrintStreamOrWriter s) {
584 // Guard against malicious overrides of Throwable.equals by
585 // using a Set with identity equality semantics.
586 Set<Throwable> dejaVu =
587 Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
588 dejaVu.add(this);
589
590 synchronized (s.lock()) {
591 // Print our stack trace
592 s.println(this);
593 StackTraceElement[] trace = getOurStackTrace();
594 for (StackTraceElement traceElement : trace)
595 s.println("\tat " + traceElement);
596
597 // Print suppressed exceptions, if any
598 for (Throwable se : getSuppressed())
599 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
600
601 // Print cause, if any
602 Throwable ourCause = getCause();
603 if (ourCause != null)
604 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
605 }
606 }
607
608 /**
609 * Print our stack trace as an enclosed exception for the specified
610 * stack trace.
611 */
612 private void printEnclosedStackTrace(PrintStreamOrWriter s,
613 StackTraceElement[] enclosingTrace,
614 String caption,
615 String prefix,
616 Set<Throwable> dejaVu) {
617 assert Thread.holdsLock(s.lock());
618 if (dejaVu.contains(this)) {
619 s.println("\t[CIRCULAR REFERENCE:" + this + "]");
620 } else {
621 dejaVu.add(this);
622 // Compute number of frames in common between this and enclosing trace
623 StackTraceElement[] trace = getOurStackTrace();
624 int m = trace.length - 1;
625 int n = enclosingTrace.length - 1;
626 while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
627 m--; n--;
628 }
629 int framesInCommon = trace.length - 1 - m;
630
631 // Print our stack trace
632 s.println(prefix + caption + this);
633 for (int i = 0; i <= m; i++)
634 s.println(prefix + "\tat " + trace[i]);
635 if (framesInCommon != 0)
636 s.println(prefix + "\t... " + framesInCommon + " more");
637
638 // Print suppressed exceptions, if any
639 for (Throwable se : getSuppressed())
640 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
641 prefix +"\t", dejaVu);
642
643 // Print cause, if any
644 Throwable ourCause = getCause();
645 if (ourCause != null)
646 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
647 }
648 }
649
650 /**
651 * Prints this throwable and its backtrace to the specified
652 * print writer.
653 *
654 * @param s {@code PrintWriter} to use for output
655 * @since JDK1.1
656 */
657 public void printStackTrace(PrintWriter s) {
658 printStackTrace(new WrappedPrintWriter(s));
659 }
730 * method. Generally speaking, the array returned by this method will
731 * contain one element for every frame that would be printed by
732 * {@code printStackTrace}.
733 *
734 * @return an array of stack trace elements representing the stack trace
735 * pertaining to this throwable.
736 * @since 1.4
737 */
738 public StackTraceElement[] getStackTrace() {
739 return getOurStackTrace().clone();
740 }
741
742 private synchronized StackTraceElement[] getOurStackTrace() {
743 // Initialize stack trace if this is the first call to this method
744 if (stackTrace == null) {
745 int depth = getStackTraceDepth();
746 stackTrace = new StackTraceElement[depth];
747 for (int i=0; i < depth; i++)
748 stackTrace[i] = getStackTraceElement(i);
749 }
750
751 return stackTrace;
752 }
753
754 /**
755 * Sets the stack trace elements that will be returned by
756 * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
757 * and related methods.
758 *
759 * This method, which is designed for use by RPC frameworks and other
760 * advanced systems, allows the client to override the default
761 * stack trace that is either generated by {@link #fillInStackTrace()}
762 * when a throwable is constructed or deserialized when a throwable is
763 * read from a serialization stream.
764 *
765 * @param stackTrace the stack trace elements to be associated with
766 * this {@code Throwable}. The specified array is copied by this
767 * call; changes in the specified array after the method invocation
768 * returns will have no affect on this {@code Throwable}'s stack
769 * trace.
770 *
771 * @throws NullPointerException if {@code stackTrace} is
772 * {@code null}, or if any of the elements of
773 * {@code stackTrace} are {@code null}
774 *
775 * @since 1.4
776 */
777 public void setStackTrace(StackTraceElement[] stackTrace) {
778 StackTraceElement[] defensiveCopy = stackTrace.clone();
779 for (int i = 0; i < defensiveCopy.length; i++) {
780 if (defensiveCopy[i] == null)
781 throw new NullPointerException("stackTrace[" + i + "]");
782 }
783
784 synchronized (this) {
785 this.stackTrace = defensiveCopy;
786 }
787 }
788
789 /**
790 * Returns the number of elements in the stack trace (or 0 if the stack
791 * trace is unavailable).
792 *
793 * package-protection for use by SharedSecrets.
794 */
795 native int getStackTraceDepth();
796
797 /**
798 * Returns the specified element of the stack trace.
799 *
800 * package-protection for use by SharedSecrets.
801 *
802 * @param index index of the element to return.
803 * @throws IndexOutOfBoundsException if {@code index < 0 ||
804 * index >= getStackTraceDepth() }
805 */
806 native StackTraceElement getStackTraceElement(int index);
807
808 /**
809 * Read a {@code Throwable} from a stream, enforcing
810 * well-formedness constraints on fields. Null entries and
811 * self-pointers are not allowed in the list of {@code
812 * suppressedExceptions}. Null entries are not allowed for stack
813 * trace elements.
814 *
815 * Note that there are no constraints on the value the {@code
816 * cause} field can hold; both {@code null} and this are valid
817 * values for the field.
818 */
819 private void readObject(ObjectInputStream s)
820 throws IOException, ClassNotFoundException {
821 s.defaultReadObject(); // read in all fields
822 List<Throwable> suppressed = null;
823 if (suppressedExceptions != null &&
824 !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
825 suppressed = new ArrayList<Throwable>(1);
826 for (Throwable t : suppressedExceptions) {
827 // Enforce constraints on suppressed exceptions in
828 // case of corrupt or malicious stream.
829 if (t == null)
830 throw new NullPointerException(NULL_CAUSE_MESSAGE);
831 if (t == this)
832 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
833 suppressed.add(t);
834 }
835 }
836
837 // If suppressed is a zero-length list, use the sentinel
838 // value.
839 if (suppressed != null && suppressed.isEmpty())
840 suppressedExceptions = suppressedSentinel;
841 else
842 suppressedExceptions = suppressed;
843
844 if (stackTrace != null) {
845 for(StackTraceElement ste : stackTrace) {
846 if (ste == null)
847 throw new NullPointerException("null StackTraceElement in serial stream. ");
848 }
849 } else { // Treat a null stack trace as a missing stack trace
850 stackTrace = new StackTraceElement[0];
851 }
852 }
853
854 /**
855 * Write a {@code Throwable} object to a stream. The stack trace
856 * will be non-{@code null}.
857 */
858 private synchronized void writeObject(ObjectOutputStream s)
859 throws IOException {
860 getOurStackTrace(); // Ensure that stackTrace field is initialized.
861 s.defaultWriteObject();
862 }
863
864 /**
865 * Adds the specified exception to the list of exceptions that
866 * were suppressed, typically by the {@code try}-with-resources
867 * statement, in order to deliver this exception.
868 *
869 * If the first exception to be suppressed is {@code null}, that
870 * indicates suppressed exception information will <em>not</em> be
871 * recorded for this exception. Subsequent calls to this method
872 * will not record any suppressed exceptions. Otherwise,
873 * attempting to suppress {@code null} after an exception has
874 * already been successfully suppressed results in a {@code
875 * NullPointerException}.
876 *
877 * <p>Note that when one exception {@linkplain
878 * #initCause(Throwable) causes} another exception, the first
879 * exception is usually caught and then the second exception is
880 * thrown in response. In contrast, when one exception suppresses
881 * another, two exceptions are thrown in sibling code blocks, such
882 * as in a {@code try} block and in its {@code finally} block, and
883 * control flow can only continue with one exception so the second
884 * is recorded as a suppressed exception of the first.
885 *
886 * @param exception the exception to be added to the list of
887 * suppressed exceptions
888 * @throws IllegalArgumentException if {@code exception} is this
889 * throwable; a throwable cannot suppress itself.
890 * @throws NullPointerException if {@code exception} is null and
891 * an exception has already been suppressed by this exception
892 * @since 1.7
893 */
894 public synchronized void addSuppressed(Throwable exception) {
895 if (exception == this)
896 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
897
898 if (exception == null) {
899 if (suppressedExceptions == suppressedSentinel) {
900 suppressedExceptions = null; // No suppression information recorded
901 return;
902 } else
903 throw new NullPointerException(NULL_CAUSE_MESSAGE);
904 } else {
905 assert exception != null && exception != this;
906
907 if (suppressedExceptions == null) // Suppressed exceptions not recorded
908 return;
909
910 if (suppressedExceptions == suppressedSentinel)
911 suppressedExceptions = new ArrayList<Throwable>(1);
912
913 assert suppressedExceptions != suppressedSentinel;
914
915 suppressedExceptions.add(exception);
916 }
917 }
918
919 private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
920
921 /**
922 * Returns an array containing all of the exceptions that were
923 * suppressed, typically by the {@code try}-with-resources
924 * statement, in order to deliver this exception.
925 *
926 * If no exceptions were suppressed, an empty array is returned.
927 *
928 * @return an array containing all of the exceptions that were
929 * suppressed to deliver this exception.
930 * @since 1.7
931 */
932 public synchronized Throwable[] getSuppressed() {
933 if (suppressedExceptions == suppressedSentinel ||
934 suppressedExceptions == null)
935 return EMPTY_THROWABLE_ARRAY;
936 else
937 return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
938 }
939 }
|