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 }
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 OutOfMemoryErrors, the three fields
175 * of Throwable that are writable in response to user actions,
176 * cause, stackTrace, and suppressedExceptions obey the following
177 * protocol:
178 *
179 * 1) The fields and initialized to a non-null sentinel value
180 *
181 * 2) Writing a null to the field indicates further writes
182 * are forbidden
183 *
184 * 3) The sentinel value may be replaced with another non-null
185 * value.
186 *
187 * For example, implementations of the HotSpot JVM have
188 * preallocated OutOfMemoryError objects to provide for better
189 * diagnosability of that situation. These objects are created
190 * without calling the constructor for that class and the fields
191 * in question are initialized to null. To support this
192 * capability, any new fields added to Throwable that require
193 * being initialized to a non-null value require a coordinated JVM
194 * 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 * This field above is lazily initialized on first use or
218 * serialization and nulled out when fillInStackTrace is called.
219 */
220
221 // Setting this static field introduces an acceptable
222 // initialization dependency on a few java.util classes.
223 private static final List<Throwable> suppressedSentinel =
224 Collections.unmodifiableList(new ArrayList<Throwable>(0));
225
226 /**
227 * The list of suppressed exceptions, as returned by
228 * {@link #getSuppressed()}.
229 *
230 * @serial
231 * @since 1.7
232 */
233 private List<Throwable> suppressedExceptions = suppressedSentinel;
234
235 /** Message for trying to suppress a null exception. */
236 private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
237
238 /** Message for trying to suppress oneself. */
239 private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
240
241 /** Caption for labeling causative exception stack traces */
242 private static final String CAUSE_CAPTION = "Caused by: ";
243
244 /** Caption for labeling suppressed exception stack traces */
245 private static final String SUPPRESSED_CAPTION = "Suppressed: ";
246
247 /**
248 * Constructs a new throwable with {@code null} as its detail message.
249 * The cause is not initialized, and may subsequently be initialized by a
250 * call to {@link #initCause}.
251 *
252 * <p>The {@link #fillInStackTrace()} method is called to initialize
253 * the stack trace data in the newly created throwable.
254 */
255 public Throwable() {
256 fillInStackTrace();
257 }
258
259 /**
260 * Constructs a new throwable with the specified detail message. The
579 */
580 public void printStackTrace(PrintStream s) {
581 printStackTrace(new WrappedPrintStream(s));
582 }
583
584 private void printStackTrace(PrintStreamOrWriter s) {
585 // Guard against malicious overrides of Throwable.equals by
586 // using a Set with identity equality semantics.
587 Set<Throwable> dejaVu =
588 Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
589 dejaVu.add(this);
590
591 synchronized (s.lock()) {
592 // Print our stack trace
593 s.println(this);
594 StackTraceElement[] trace = getOurStackTrace();
595 for (StackTraceElement traceElement : trace)
596 s.println("\tat " + traceElement);
597
598 // Print suppressed exceptions, if any
599 for (Throwable se : getSuppressed())
600 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
601
602 // Print cause, if any
603 Throwable ourCause = getCause();
604 if (ourCause != null)
605 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
606 }
607 }
608
609 /**
610 * Print our stack trace as an enclosed exception for the specified
611 * stack trace.
612 */
613 private void printEnclosedStackTrace(PrintStreamOrWriter s,
614 StackTraceElement[] enclosingTrace,
615 String caption,
616 String prefix,
617 Set<Throwable> dejaVu) {
618 assert Thread.holdsLock(s.lock());
619 if (dejaVu.contains(this)) {
620 s.println("\t[CIRCULAR REFERENCE:" + this + "]");
621 } else {
622 dejaVu.add(this);
623 // Compute number of frames in common between this and enclosing trace
624 StackTraceElement[] trace = getOurStackTrace();
625 int m = trace.length - 1;
626 int n = enclosingTrace.length - 1;
627 while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
628 m--; n--;
629 }
630 int framesInCommon = trace.length - 1 - m;
631
632 // Print our stack trace
633 s.println(prefix + caption + this);
634 for (int i = 0; i <= m; i++)
635 s.println(prefix + "\tat " + trace[i]);
636 if (framesInCommon != 0)
637 s.println(prefix + "\t... " + framesInCommon + " more");
638
639 // Print suppressed exceptions, if any
640 for (Throwable se : getSuppressed())
641 se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
642 prefix +"\t", dejaVu);
643
644 // Print cause, if any
645 Throwable ourCause = getCause();
646 if (ourCause != null)
647 ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
648 }
649 }
650
651 /**
652 * Prints this throwable and its backtrace to the specified
653 * print writer.
654 *
655 * @param s {@code PrintWriter} to use for output
656 * @since JDK1.1
657 */
658 public void printStackTrace(PrintWriter s) {
659 printStackTrace(new WrappedPrintWriter(s));
660 }
793 */
794 native int getStackTraceDepth();
795
796 /**
797 * Returns the specified element of the stack trace.
798 *
799 * package-protection for use by SharedSecrets.
800 *
801 * @param index index of the element to return.
802 * @throws IndexOutOfBoundsException if {@code index < 0 ||
803 * index >= getStackTraceDepth() }
804 */
805 native StackTraceElement getStackTraceElement(int index);
806
807 private void readObject(ObjectInputStream s)
808 throws IOException, ClassNotFoundException {
809 s.defaultReadObject(); // read in all fields
810 List<Throwable> suppressed = null;
811 if (suppressedExceptions != null &&
812 !suppressedExceptions.isEmpty()) { // Copy Throwables to new list
813 suppressed = new ArrayList<Throwable>(1);
814 for (Throwable t : suppressedExceptions) {
815 // Enforce constraints on suppressed exceptions in
816 // case of corrupt or malicious stream.
817 if (t == null)
818 throw new NullPointerException(NULL_CAUSE_MESSAGE);
819 if (t == this)
820 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
821 suppressed.add(t);
822 }
823 }
824
825 // If suppressed is a zero-length list, use the sentinel
826 // value.
827 if (suppressed != null && suppressed.isEmpty())
828 suppressedExceptions = suppressedSentinel;
829 else
830 suppressedExceptions = suppressed;
831
832 // Note that there are no constraints on the value the cause
833 // field can hold; both null and this are valid values for the
834 // field.
835 }
836
837 private synchronized void writeObject(ObjectOutputStream s)
838 throws IOException
839 {
840 getOurStackTrace(); // Ensure that stackTrace field is initialized.
841 s.defaultWriteObject();
842 }
843
844 /**
845 * Adds the specified exception to the list of exceptions that
846 * were suppressed, typically by the {@code try}-with-resources
847 * statement, in order to deliver this exception.
848 *
849 * If the first exception to be suppressed is {@code null}, that
850 * indicates suppressed exception information will <em>not</em> be
851 * recorded for this exception. Subsequent calls to this method
852 * will not record any suppressed exceptions. Otherwise,
853 * attempting to suppress {@code null} after an exception has
854 * already been successfully suppressed results in a {@code
855 * NullPointerException}.
856 *
857 * <p>Note that when one exception {@linkplain
858 * #initCause(Throwable) causes} another exception, the first
859 * exception is usually caught and then the second exception is
860 * thrown in response. In contrast, when one exception suppresses
861 * another, two exceptions are thrown in sibling code blocks, such
862 * as in a {@code try} block and in its {@code finally} block, and
863 * control flow can only continue with one exception so the second
864 * is recorded as a suppressed exception of the first.
865 *
866 * @param exception the exception to be added to the list of
867 * suppressed exceptions
868 * @throws IllegalArgumentException if {@code exception} is this
869 * throwable; a throwable cannot suppress itself.
870 * @throws NullPointerException if {@code exception} is null and
871 * an exception has already been suppressed by this exception
872 * @since 1.7
873 */
874 public synchronized void addSuppressed(Throwable exception) {
875 if (exception == this)
876 throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
877
878 if (exception == null) {
879 if (suppressedExceptions == suppressedSentinel) {
880 suppressedExceptions = null; // No suppression information recorded
881 return;
882 } else
883 throw new NullPointerException(NULL_CAUSE_MESSAGE);
884 } else {
885 assert exception != null && exception != this;
886
887 if (suppressedExceptions == null) // Suppressed exceptions not recorded
888 return;
889
890 if (suppressedExceptions == suppressedSentinel)
891 suppressedExceptions = new ArrayList<Throwable>(1);
892
893 assert suppressedExceptions != suppressedSentinel;
894
895 suppressedExceptions.add(exception);
896 }
897 }
898
899 private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
900
901 /**
902 * Returns an array containing all of the exceptions that were
903 * suppressed, typically by the {@code try}-with-resources
904 * statement, in order to deliver this exception.
905 *
906 * If no exceptions were suppressed, an empty array is returned.
907 *
908 * @return an array containing all of the exceptions that were
909 * suppressed to deliver this exception.
910 * @since 1.7
911 */
912 public synchronized Throwable[] getSuppressed() {
913 if (suppressedExceptions == suppressedSentinel ||
914 suppressedExceptions == null)
915 return EMPTY_THROWABLE_ARRAY;
916 else
917 return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
918 }
919 }
|